【发布时间】:2016-03-21 09:53:15
【问题描述】:
我问这个问题是因为我还没有找到一个关于如何注释分组水平 Pandas 条形图的工作示例。我知道以下两个:
但它们都是关于垂直条形图的。即,要么没有水平条形图的解决方案,要么没有完全工作。
在解决这个问题几周后,我终于可以用示例代码提出问题,这几乎是我想要的,只是不是 100% 有效。需要您的帮助才能达到 100%。
我们来了,full code is uploaded here。结果如下所示:
您可以看到它几乎可以工作,只是标签没有放在我想要的位置,我自己无法将它们移动到更好的位置。此外,因为图表栏的顶部是用来显示错误栏的,所以我真正想要的是将注释文本移向 y 轴,整齐地排列在左侧或右侧y 轴,取决于 X 值。例如,这是我的同事可以使用 MS Excel 执行的操作:
Python 可以用 Pandas 图表做到这一点吗?
我将上面网址中的代码包含在注释中,一个是我能做的一切,另一个是参考(来自In [23]):
# my all-that-I-can-do
def autolabel(rects):
#if height constant: hbars, vbars otherwise
if (np.diff([plt.getp(item, 'width') for item in rects])==0).all():
x_pos = [rect.get_x() + rect.get_width()/2. for rect in rects]
y_pos = [rect.get_y() + 1.05*rect.get_height() for rect in rects]
scores = [plt.getp(item, 'height') for item in rects]
else:
x_pos = [rect.get_width()+.3 for rect in rects]
y_pos = [rect.get_y()+.3*rect.get_height() for rect in rects]
scores = [plt.getp(item, 'width') for item in rects]
# attach some text labels
for rect, x, y, s in zip(rects, x_pos, y_pos, scores):
ax.text(x,
y,
#'%s'%s,
str(round(s, 2)*100)+'%',
ha='center', va='bottom')
# for the reference
ax.bar(1. + np.arange(len(xv)), xv, align='center')
# Annotate with text
ax.set_xticks(1. + np.arange(len(xv)))
for i, val in enumerate(xv):
ax.text(i+1, val/2, str(round(val, 2)*100)+'%', va='center',
ha='center', color='black')
请帮忙。谢谢。
【问题讨论】:
标签: python pandas plot bar-chart