熊猫,条形图注释

时间:2015-12-05 22:23:21

标签: pandas matplotlib plot charts

如何正确地为Pandas Bar Charts提供注释?

我跟随Bar Chart Annotations with Pandas and MPL,但不知怎的,我无法将其变成我自己的代码 - this is as far as I can go。怎么了?

我还发现了以下代码from here

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朱,答案。但是,在水平条中,您仍然将文本放在条形图的顶部,但是我需要在其中或沿着它们显示文本,如我引用的文章中所示,

enter image description here

他/她说,

  

"我对水平条形图非常了解,因为我认为它们更容易阅读,但我知道很多人宁愿在常规条形图中看到这个图表。所以,这是执行此操作的代码;你会注意到为了创建注释而改变了一些东西" *

1 个答案:

答案 0 :(得分:2)

您的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)

enter image description here

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)

enter image description here