我目前正在制作一个有点简单的条形图,但我想在相应的条形图上方添加平均值和标准差文本。问题是,我的图表中的条形图的大小并不完全相同,所以我不能使用rectangle对象来定义高度。这样做会产生如下所示的图像:
当然,这是完全不可接受的,所以我一直在试图找到一种方法来做同样的事情,除了错误栏的盖子。
我当前的代码是:
bar = plt.bar(names, means, yerr=sterr, capsize=5, color=colors)
plt.yticks(np.arange(0,0.35,step=0.05))
plt.ylabel('Percentage of appearance')
plt.xlabel('Pot in question')
# Add numbers in plot
for i, rectangle in enumerate(bar):
height = rectangle.get_height()
plt.text(rectangle.get_x() + rectangle.get_width()/2, height+0.01,
'$\mu=$%s \n $\sigma=$%s' % (str(round(height,3))[1:], str(round(sterr[i],3))[1:]),
ha='center', va='bottom')
plt.show()
新代码将用误差条形图的上限替换for循环中的矩形。
继续我的尝试,我打开了BarContainer对象,并找到了以下内容:
{'patches': [<matplotlib.patches.Rectangle object at 0x0000020C44BB8CF8>, <matplotlib.patches.Rectangle object at 0x0000020C44BB8FD0>, <matplotlib.patches.Rectangle object at 0x0000020C44BC6390>, <matplotlib.patches.Rectangle object at 0x0000020C44BC66D8>, <matplotlib.patches.Rectangle object at 0x0000020C44BC6A20>, <matplotlib.patches.Rectangle object at 0x0000020C44BC6DA0>, <matplotlib.patches.Rectangle object at 0x0000020C44BD4160>, <matplotlib.patches.Rectangle object at 0x0000020C44BD44E0>], 'errorbar': <ErrorbarContainer object of 3 artists>, 'eventson': False, '_oid': 0, '_propobservers': {}, '_remove_method': <function _AxesBase.add_container.<locals>.<lambda> at 0x0000020C3F71EF28>, '_label': '_container1'}
它有一个ErrorbarContainer对象,所以我试着打开它,显示如下:
{'lines': (None, (<matplotlib.lines.Line2D object at 0x0000020C44BD4DA0>, <matplotlib.lines.Line2D object at 0x0000020C44BD4EB8>), (<matplotlib.collections.LineCollection object at 0x0000020C44BD4860>,)), 'has_xerr': False, 'has_yerr': True, 'eventson': False, '_oid': 0, '_propobservers': {}, '_remove_method': None, '_label': '_nolegend_'}
但这些都没有给我任何关于如何继续进行的想法。
发布于 2018-08-02 08:35:19
是否按错误条的高度缩放文本位置?
names = ['bob', 'sharon', 'han solo', 'the dude']
means = [14, 13, 1, 22]
sterr = [1, 3, 5, 1.4]
colors = ['red','green','blue','pink']
bar = plt.bar(names, means, yerr=sterr, capsize=5, color=colors)
plt.yticks(np.arange(0,0.35,step=0.05))
plt.ylabel('Percentage of appearance')
plt.xlabel('Pot in question')
# Add numbers in plot
for i, rectangle in enumerate(bar):
height = rectangle.get_height()
plt.text(rectangle.get_x() + rectangle.get_width()/2, height+sterr[i] + 0.3,
'$\mu=$%s \n $\sigma=$%s' % (str(round(height,3))[1:], str(round(sterr[i],3))[1:]),
ha='center', va='bottom')
plt.show()
这是艰难的,但你明白了。我估计,这个图显示了问题的解决方案,并使用虚构的数据生成了更多的解决方案。
https://stackoverflow.com/questions/51643995
复制相似问题