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

ler*_*ygr 60 python plot matplotlib dataframe pandas

我正在寻找一种方法来使用我的DataFrame中的舍入数值来在Pandas条形图中注释我的条形图.

>>> 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
Run Code Online (Sandbox Code Playgroud)

我想得到这样的东西:

条形图注释示例

我尝试使用此代码示例,但注释都集中在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')
Run Code Online (Sandbox Code Playgroud)

Tom*_*ger 98

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

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

你需要调整字符串格式和偏移以使事物居中,也许使用宽度p.get_width(),但这应该让你开始.除非您在某处跟踪偏移,否则它可能不适用于堆积条形图.

  • 感谢@TomAugsPurger,以下工作:`for ax.patches:ax.annotate(np.round(p.get_height(),decimals = 2),(p.get_x()+ p.get_width()/ 2). ,p.get_height()),ha ='center',va ='center',xytext =(0,10),textcoords ='offset points')` (15认同)
  • 我发现这适用于barh:`ax.annotate(str(p.get_width()),(p.get_x()+ p.get_width(),p.get_y()),xytext =(5,10), textcoords ='偏移点')` (4认同)
  • 你会如何为 ax = df.plot(kind='barh') 做到这一点? (3认同)
  • 另一个问题:如何处理负值的小节?使用上面的代码,即使条形值为负,标签也始终具有正坐标。 (2认同)
  • 谢谢@capitalistpug。我发现添加水平对齐使你的更好。`ax.annotate(str(int(p.get_width())), (p.get_x() + p.get_width(), p.get_y()), xytext=(-2, 4), textcoords='offset点',horizo​​ntalalignment='right')` +1 (2认同)

two*_*rec 25

采用样品浮法成型处理的解决方案也可以处理负值.

仍然需要调整补偿.

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))
Run Code Online (Sandbox Code Playgroud)

价值标签条形图


tdy*_*tdy 15

从 matplotlib 3.4.0 开始:

Axes.bar_label为自动标记条形图添加了新的辅助方法。

对于单组条形图,请提供ax.containers[0]

df = pd.DataFrame({'A': np.random.rand(2)}, index=['value1', 'value2'])
ax = df.plot.barh()

ax.bar_label(ax.containers[0])
Run Code Online (Sandbox Code Playgroud)

对于多组条形图,迭代ax.containers

df = pd.DataFrame({'A': np.random.rand(2), 'B': np.random.rand(2)}, index=['value1', 'value2'])
ax = df.plot.bar()

for container in ax.containers:
    ax.bar_label(container)
Run Code Online (Sandbox Code Playgroud)

bar_label 示例

有关使用可选样式参数的综合示例,请参阅matplotlib 的条形标签演示

Axes.bar_label(self, container, labels=None, *, fmt='%g', label_type='edge', padding=0, **kwargs)