如何正确给熊猫条形图添加注释?
我正在使用Pandas和MPL进行条形图注释,但是某种程度上我不能将它纳入我自己的代码中-这是我所能做到的。怎么了?
我还从这里找到了以下代码:
def autolabel(rects):
# attach some text labels
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
'%d' % int(height),
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
但是我也不怎么将其应用到我的代码中。请帮忙。
更新:
谢谢@CT朱,谢谢您的回答。但是,在您的水平栏中,您仍将文本放置在水平条上方,但是我需要将文本显示在水平条中或沿水平条显示,就像我所引用的文章中所说的那样,
他/他在哪里说,
“对于水平条形图,我非常看重,因为我确实认为它们更易于阅读,但是,我了解到,很多人都希望看到此条形图以常规条形图实现。因此,这里是执行此操作的代码;您会注意到为了创建注释,有些事情已经更改“ *
看来您的autolabel
函数需要一个列表patches
,假设您的绘图仅是这些柱形图patches
,我们可以这样做:
df = pd.DataFrame({'score':np.random.randn(6),
'person':[x*3 for x in list('ABCDEF')]})
def autolabel(rects):
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]
#if height constant: hbars, vbars otherwise
if (np.diff([plt.getp(item, 'width') for item in rects])==0).all():
scores = [plt.getp(item, 'height') for item in rects]
else:
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,
ha='center', va='bottom')
ax = df.set_index(['person']).plot(kind='barh', figsize=(10,7),
color=['dodgerblue', 'slategray'], fontsize=13)
ax.set_alpha(0.8)
ax.set_title("BarH")#,fontsize=18)
autolabel(ax.patches)
ax = df.set_index(['person']).plot(kind='bar', figsize=(10,7),
color=['dodgerblue', 'slategray'], fontsize=13)
ax.set_alpha(0.8)
ax.set_title("Bar")#,fontsize=18)
autolabel(ax.patches)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句