【发布时间】:2021-08-13 08:05:53
【问题描述】:
我正在尝试制作一个大致像这样的图表。
以下是一些示例数据:
data = {
"date": ["2020-07-01", "2020-07-01", "2020-07-01", "2020-08-01", "2020-08-01", "2020-08-01", "2020-09-01",
"2020-09-01", "2020-09-01", "2020-10-01", "2020-10-01", "2020-10-01", "2020-11-01", "2020-11-01",
"2020-11-01", "2020-12-01", "2020-12-01", "2020-12-01", "2021-01-01", "2021-01-01", "2021-01-01",
"2021-02-01", "2021-02-01", "2021-02-01", "2021-03-01", "2021-03-01", "2021-03-01", "2021-04-01",
"2021-04-01", "2021-04-01", "2021-05-01", "2021-05-01", "2021-05-01", "2021-06-01", "2021-06-01",
"2021-06-01"],
"col2": ["A", "B", "C", "A", "B", "C", "A", "B", "C", "A", "B", "C", "A", "B", "C", "A", "B", "C", "A", "B", "C",
"A", "B", "C", "A", "B", "C", "A", "B", "C", "A", "B", "C", "A", "B", "C"],
"col3": [24, 45, 0.0, 18, 47, 0.0, 31, 50, 0.0, 21, 40, 565, 34, 64, 220, 724, 3598, 1493,
286, 127, 185, 37, 94, 233, 22, 18, 170, 111, 45, 186, 17, 106, 114, 12, 50, 122]
}
我使用这段代码来制作多索引数据框,我还需要一个日期时间索引来格式化 x 轴。
df = pd.DataFrame(data)
df["date"] = pd.to_datetime(df["date"])
df = df.groupby(["date", "col2"]).sum()
df_single_index = df.groupby("date").sum()
这是我必须制作大部分图表的代码:
fig, ax = plt.subplots(figsize=(11.96, 4.42))
df.unstack().plot(kind='bar', ax=ax, stacked=True, zorder=3)
ax.set_xticks(range(df_single_index.index.size))
ax.set_xticklabels([date.strftime('%b\n%Y') if date.year != df_single_index.index[idx - 1].year
else date.strftime('%b') for idx, date in enumerate(df_single_index.index)])
ax.figure.autofmt_xdate(rotation=0, ha='center')
ax.tick_params(axis='x', which="major", bottom=False)
x_locator = FixedLocator(np.arange(-0.5, (len(df_single_index) + 0.5), 1))
ax.tick_params(axis='x', which="minor", direction="out", length=15, width=1)
ax.xaxis.set_minor_locator(x_locator)
plt.grid(which="major", axis="y", zorder=0)
大多数工作正常,除了图例看起来不太好。
添加此代码修复了图例并更改了图例的颜色:
colors = {"A": (1, 0.75, 0), "B": (0.498, 0.498, 0.498), "C": (0, 0.7, 0.76)}
labels = list(colors.keys())
handles = [plt.Rectangle((0, 0), 1, 1, color=colors[label]) for label in labels]
plt.legend(handles, labels)
但是现在条形图与图例不匹配,并且在图表中添加颜色字典作为参数只会引发 KeyError。我不知道该怎么做。任何建议将不胜感激。
【问题讨论】:
标签: python pandas dataframe plot