Annotate bars with values on Pandas bar plots

后端 未结 3 1235
甜味超标
甜味超标 2020-11-22 06:26

I was looking for a way to annotate my bars in a Pandas bar plot with the rounded numerical values from my DataFrame.

>>> df=pd.DataFrame({\'A\':np.         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 07:00

    Solution which also handles the negative values with sample float formatting.

    Still needs tweaking offsets.

    df=pd.DataFrame({'A':np.random.rand(2)-1,'B':np.random.rand(2)},index=['val1','val2'] )
    ax = df.plot(kind='bar', color=['r','b']) 
    x_offset = -0.03
    y_offset = 0.02
    for p in ax.patches:
        b = p.get_bbox()
        val = "{:+.2f}".format(b.y1 + b.y0)        
        ax.annotate(val, ((b.x0 + b.x1)/2 + x_offset, b.y1 + y_offset))
    

提交回复
热议问题