我正在尝试创建一个代表 2 个不同数据集的图。它们已作为 2 个单独的迹线添加。第一个是一个简单的散点图,第二个是一系列矩形,我想根据“分类”值以不同的方式对其进行着色。矩形代表“事件”的持续时间。我可以使用 fillcolor 选项为矩形着色,但目前我似乎只能将颜色设置为单个值,例如‘红色’。
2 个数据框看起来像这样:
df1
Datetime, Frequency_hz
15/08/2023 09:09:22, 1575422000
15/08/2023 10:10:32, 1575452000
15/08/2023 10:10:35, 1572322000
15/08/2023 11:11:54, 1575432000
events_df
Date_Start_Time, Date_End_Time, Classification, Band
15/08/2023 09:23:22,15/08/2023 09:35:12, Class 1,A
15/08/2023 09:43:40,15/08/2023 09:50:47, Class 2,A
15/08/2023 10:13:44,15/08/2023 10:15:32, Class 3,A
15/08/2023 11:33:11,15/08/2023 11:39:23, Class 4,B
My code looks like this:
# Loading data
DATA = 'C:\work\20230815_UTC.csv'
EVENT_DATA = r"C:\work\events.csv"
BAND = 'A'
df = pd.read_csv(DATA)
events_df = pd.read_csv(EVENT_DATA)
# Filter for band
events_df = events_df[(events_df['Band'] == BAND)]
# Filter data for specific weekday
events_df = events_df.loc[events_df['Date_Start_time'].dt.weekday == 1] # 1= Tues, 2=Wed, 3=Thurs
df = pd.read_csv(DATA)
# Create plots
fig1 = go.Figure()
fig1.add_scatter(
x=df1.Datetime,
y=df1.Frequency_hz,
mode="markers",
name="Points",
showlegend=True
)
# Dictionary for colouring classes
colours = {'Class 1':'red','Class 2':'violet',
'Class 3':'aqua','Class 4':'brown'}
# Loop through events table and plot
for i in events_df.index:
start_time = events_df.loc[i,"Date_Start_time"]
end_time = events_df.loc[i,"Date_End_time"]
colour = events_df.loc[i,"Classification"]
fig1.add_vrect(x0=start_time,
x1=end_time,
fillcolor=colours['Classification'],
opacity=0.5,
name='Events'
)
# Update various layout parameters
fig1.update_layout(
title=f"Events on 15th August 2023",
xaxis_title="Time (UTC)",
yaxis_title="Frequency (Hz)",
font=dict(
family="Courier New, monospace",
size=18,
color="RebeccaPurple"
)
)
fig1.show()
我的代码显示我已经创建了一个字典“颜色”,并且在循环中我尝试将 fillcolor 选项的值设置为“分类”值。这不起作用,我收到一条“KeyError:‘分类’消息。如果我将填充颜色设置为“红色”,它可以工作,但所有矩形都为红色。有人对我如何做到这一点有任何建议吗?
非常感谢
您需要迭代分类列而不仅仅是索引
for idx, vals in events_df['Classification'].items():
start_time = events_df.loc[idx,"Date_Start_Time"]
end_time = events_df.loc[idx,"Date_End_Time"]
colour = events_df.loc[idx,"Classification"]
fig1.add_vrect(x0=start_time,
x1=end_time,
fillcolor=colours[vals],
opacity=0.5,
name='Events'
)