【发布时间】:2022-01-16 20:46:37
【问题描述】:
我有一个这样的数据框字典
{'region': {0: 'R0',1: 'R1',2: 'R2',3: 'R3',4: 'R4',5: 'R5',6: 'R6'},
'DT': {0: 0.765, 1: 0.694, 2: 0.778, 3: 0.694, 4: 0.629, 5: 0.67, 6: 0.668},
'GB': {0: 0.714, 1: 0.741, 2: 0.752, 3: 0.741, 4: 0.683, 5: 0.706, 6: 0.656},
'KNN': {0: 0.625, 1: 0.641, 2: 0.628, 3: 0.641, 4: 0.552, 5: 0.544, 6: 0.578},
'LR': {0: 0.624, 1: 0.662, 2: 0.634, 3: 0.662, 4: 0.581, 5: 0.629, 6: 0.649},
'lstm': {0: 0.803,1: 0.633,2: 0.845,3: 0.668,4: 0.717,5: 0.726,6: 0.674}}
格式简洁
region DT GB KNN LR lstm
0 R0 0.765 0.714 0.625 0.624 0.803
1 R1 0.694 0.741 0.641 0.662 0.633
2 R2 0.778 0.752 0.628 0.634 0.845
3 R3 0.694 0.741 0.641 0.662 0.668
4 R4 0.629 0.683 0.552 0.581 0.717
5 R5 0.67 0.706 0.544 0.629 0.726
6 R6 0.668 0.656 0.578 0.649 0.674
我想绘制带有误差线的堆积条形图。这个数据框没有关于标准差的信息,但我有另一个标准差数据框。
假设有两个数据框的均值和标准差
我试过这段代码
fig, ax = plt.subplots()
width=0.5
clfs=['DT', 'KNN', 'LR', 'GB', 'lstm']
ax.bar(mean_df['region'], mean_df[clfs[0]], width,yerr=std_df[clfs[0]], label=clfs[0])
for i in range(1,5):
ax.bar(mean_df['region'], mean_df[clfs[i]], width,yerr=std_df[clfs[i]], label=clfs[i],bottom=mean_df[clfs[i-1]])
plt.xticks(rotation=90)
plt.legend()
plt.show()
但是条形图没有正确堆叠。我也在寻找一种在每个条形段上写入值的方法,以增加绘图的可读性
编辑: 解决方案是在绘制第三个列表时在底部添加前两个列表。
fig, ax = plt.subplots()
ax.bar(mean_df['region'], mean_df[clfs[0]], width,yerr=std_df[clfs[0]], label=clfs[0])
ax.bar(mean_df['region'], mean_df[clfs[1]], width,yerr=std_df[clfs[1]], label=clfs[1],bottom=mean_df[clfs[0]])
ax.bar(mean_df['region'], mean_df[clfs[2]], width,yerr=std_df[clfs[2]], label=clfs[2],
bottom=mean_df[clfs[0]]+mean_df[clfs[1]])
但我正在寻找一种优雅的方式来做到这一点,以及如何在栏的片段上写入值
编辑 2: 我来了
ax = mean_df.plot(kind='bar', stacked=True, figsize=(8, 6),yerr=std_df, rot=0, xlabel='region', ylabel='DT')
但现在我正在寻找编写文本的方法。 我试过这个
for c in ax.containers:
ax.bar_label(c, label_type='center')
但我得到了这个错误
AttributeError: 'ErrorbarContainer' object has no attribute 'patches'
编辑 3
这个错误是因为yerr=std_df,但我也想保留错误栏
【问题讨论】:
标签: python pandas matplotlib annotations bar-chart