问题描述
我一直在寻找一种方法,用我的 DataFrame 中的舍入数值来注释 Pandas 条形图中的条形.
>>>df=pd.DataFrame({'A':np.random.rand(2),'B':np.random.rand(2)},index=['value1','value2'])>>>df甲乙值 1 0.440922 0.911800值 2 0.588242 0.797366我想得到这样的东西:
我尝试使用此代码示例,但注释都以 x 刻度为中心:
>>>ax = df.plot(kind='bar')>>>对于 idx,enumerate(list(df.index)) 中的标签:对于 df.columns 中的 acc:值 = np.round(df.ix[idx][acc],decimals=2)ax.annotate(值,(idx, 值),xytext=(0, 15),textcoords='偏移点')您可以直接从轴的补丁中获取它:
for p in ax.patches:ax.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005))
您需要调整字符串格式和偏移量以使内容居中,也许可以使用 p.get_width()
中的宽度,但这应该会让您开始.除非您在某处跟踪偏移量,否则它可能不适用于堆叠条形图.
I was looking for a way to annotate my bars in a Pandas bar plot with the rounded numerical values from 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 code sample, but the annotations are all centered on the x ticks:
>>> 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')
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.
这篇关于在 Pandas 条形图上用值注释条形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!