python - 使用 pyplot 在误差线帽上方打印文本
问题描述
我目前正在制作一个有点简单的条形图,但我想在相应的条形上方添加平均值和标准差文本。问题是我的图表中的条形大小不一样,所以我不能使用矩形对象来定义高度。这样做会产生如下图像:
当然,这是完全不能接受的,所以我一直在尝试找到一种方法来做同样的事情,除了误差线的上限。
我目前的代码是这样的:
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_'}
但是这些都没有给我任何关于如何进行的想法。
解决方案
按误差线的高度缩放文本的位置?
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()
这很粗糙,但你明白了。我认为,该图显示了您的问题的解决方案,并使用组成的数据生成了更多。
推荐阅读
- laravel - 在同一服务器的子目录中托管多个 laravel 项目
- javascript - 尝试运行 npm install discord.io winston -save 时出错
- excel - 如何将此代码从使用 5 个常量更改为它们的平均值?
- python - 尝试除了不赶上功能?
- vue.js - 我可以使用使用 VueX 的组件,而我的应用程序也使用 VueX 吗?
- python - 如何将多个 QPixmap 放在继承自 QtWidgets.QGraphicsPixmapItem 的类中?
- c++ - 从一个案例到另一个案例获取信息
- python - Django模板没有迭代对象
- android - 滚动屏幕后执行操作
- lotus-notes - 仅显示两个值单选按钮的一个单选按钮值