我正在寻找一种方法,用我的 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
我想得到这样的东西:
我尝试使用此代码示例,但注释都以 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')
最佳答案
您可以直接从轴的补丁中获得它:
for p in ax.patches:
ax.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005))
您需要调整字符串格式和偏移量以使事物居中,也许使用 p.get_width()
中的宽度,但这应该可以帮助您入门。除非您在某处跟踪偏移量,否则它可能不适用于堆积条形图。
关于python - 在 Pandas 条形图上用值注释条形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25447700/