【问题标题】:Pandas, Bar Chart AnnotationsPandas,条形图注释
【发布时间】:2016-03-10 18:14:30
【问题描述】:

如何正确地给 Pandas 条形图添加注释?

我正在关注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 Zhu 的回答。但是,在您的水平条中,您仍然将文本放在条的顶部,但我需要在它们内部或沿它们显示文本,就像我参考的文章中的这样,

他/她在哪里说,

“我非常喜欢水平条形图,因为我真的认为它们更容易阅读,但是,我知道很多人宁愿看到这个图表在常规条形图中实现。所以,这里是代码这样做;您会注意到为了创建注释而进行了一些更改"*

【问题讨论】:

    标签: pandas matplotlib plot charts


    【解决方案1】:

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

    【讨论】:

    • 谢谢!根据上述 Pandas 和 MPL 的条形图注释autolabel 对于垂直和水平条形将是不同的。显然,我复制的代码是用于竖线的。您能否将其更改为水平条,以便文本显示在 within 或沿条而不是在其顶部?另外,为什么值都是0.5?我需要用scores 的实际值进行注释。谢谢
    • 查看编辑。这只需要确定该图是条形图还是条形图。
    • 谢谢@CT Zhu 的回答。我更新了我的 OP 以进一步解释我所说的“在栏内或沿栏”
    • 好的,我可以解决这个问题。再次感谢@CT Zhu。
    猜你喜欢
    • 2018-05-16
    • 2019-12-23
    • 2014-10-16
    • 2017-01-23
    相关资源
    最近更新 更多