用Pandas条形图上的值来标注条形图

我正在寻找一种方法在我的DataFrame中使用值(舍入)在Pandas条形图中标注我的条形图。

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

我想得到这样的东西:

条形图标注示例

我尝试了这个,但注释都集中在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') 

你直接从轴的补丁中得到它:

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

你会想要调整string格式和偏移量以获得中心,也许使用p.get_width()的宽度,但是这应该让你开始。 除非你跟踪偏移量,否则可能不会与堆积的堰坝一起工作。

解决scheme也处理样本浮动格式化的负值。

仍然需要调整抵消。

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

值标注的条形图