用Pandas条形图上的值注释条形图

2024-03-29 10:46:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种方法,用数据框中的舍入数值来注释熊猫条形图中的条形图。

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

我想买这样的东西:

bar plot annotation example

我试过这个代码示例,但是注释都集中在x记号上:

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

Tags: 方法indfforindexvaluenprandom
2条回答

直接从轴的补丁中获得:

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

您可能需要调整字符串格式和偏移量以使其居中,也可以使用p.get_width()中的宽度,但这应该可以帮助您开始。它可能不适用于堆叠条形图,除非您跟踪某个位置的偏移。

解决方案,该解决方案还使用示例浮点格式处理负值。

仍然需要调整偏移。

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

value labeled bar plot

相关问题 更多 >