Python 在 Pandas 条形图上用值注释条形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25447700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Annotate bars with values on Pandas bar plots
提问by leroygr
I was looking for a way to annotate my bars in a Pandas bar plot with the rounded numerical values from my DataFrame.
我一直在寻找一种方法,用我的 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
I would like to get something like this:
我想得到这样的东西:


I tried with this code sample, but the annotations are all centered on the x ticks:
我尝试使用此代码示例,但注释都集中在 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')
采纳答案by TomAugspurger
You get it directly from the axes' patches:
您可以直接从轴的补丁中获取它:
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. It may not work with stacked bar plots unless you track the offsets somewhere.
您需要调整字符串格式和偏移量以使事物居中,也许可以使用 from 的宽度p.get_width(),但这应该可以帮助您入门。除非您在某处跟踪偏移量,否则它可能不适用于堆叠条形图。
回答by tworec
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))

