Annotate bars with values on Pandas bar plots

匿名 (未验证) 提交于 2019-12-03 02:50:02

问题:

I looking for a way to annotate my bars in a Pandas bar plot with the values (rounded) in my DataFrame.

>>> df=pd.DataFrame({'A':np.random.rand(2),'B':np.random.rand(2)},index=['value1','value2'] )          >>> df                  A         B   value1  0.440922  0.911800   value2  0.588242  0.797366 

I would like to get something like this:

I tried with this, but the annotations are all centered on the xthicks:

>>> ax = df.plot(kind='bar')  >>> for idx, label in enumerate(list(df.index)):          for acc in df.columns:             value = np.round(df.ix[idx][acc],decimals=2)             ax.annotate(value,                         (idx, value),                          xytext=(0, 15),                           textcoords='offset points') 

回答1:

You get it directly from the axes' patches:

In [35]: for p in ax.patches:     ax.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005)) 

You'll want to tweak the string formatting and the offsets to get things centered, maybe use the width from p.get_width(), but that should get you started. May not worked with stacked barplots unless you track the offsets somewhere.



回答2:

Solution wich handles also negative values with sample float formating.

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



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!