【发布时间】:2021-08-05 03:32:37
【问题描述】:
python==3.8,情节==4.14.3
MRE:
start_date = "20210716"
end_date = "20210730"
date_range = pd.date_range(start=start_date, end=end_date).strftime("%Y%m%d")
A = np.random.randint(1, 100, size=len(date_range)*2)
B = np.random.randint(1, 100, size=len(date_range)*2)
names = ["albert", "chris"]
C = names*(len(date_range))
df = pd.DataFrame({"date":list(date_range)*2,
"A":A,
"B":B,
"C":C})
df["date"] = pd.to_datetime(df["date"], format="%Y%m%d")
df.set_index(["date"], inplace=True)
df.sort_index(inplace=True)
看起来像这样:
A B C
date
2021-07-16 48 62 Albert
2021-07-16 23 44 Chris
2021-07-17 7 21 Albert
2021-07-17 5 99 Chris
2021-07-18 9 28 Albert
...
我想用以下内容创建一个子图
- 以 A 列为 y 轴的散点图
- 以 B 列为 y 轴的散点图
- 散点图中的每一行都使用 columnC 着色
大多数类似问题的答案都使用 clustered.iplot 或 plotly express。我想坚持plotly.graph_objects。
这是我的看法:
colors = ["blue", "yellow"]
fig = make_subplots(rows=2, cols=1)
for i, col in enumerate(["A", "B"]):
for name, color in zip(names, colors):
n_df = df.loc[df["C"] == name].copy()
fig.add_trace(
go.Scatter(
name = f"{i}_{name}",
x = n_df.index,
y = n_df[col],
marker_color = color
),
row=i+1, col=1
)
fig.update_yaxes(title_text=col, row=i+1, col=1)
fig.show()
这可以完成工作,但是随着更多名字的出现,我不想每次都添加新颜色。 有没有更容易维护的方法?
【问题讨论】: