首页 > 解决方案 > 使用 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_'}

但是这些都没有给我任何关于如何进行的想法。

标签: pythonmatplotlib

解决方案


按误差线的高度缩放文本的位置?

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()

在此处输入图像描述

这很粗糙,但你明白了。我认为,该图显示了您的问题的解决方案,并使用组成的数据生成了更多。


推荐阅读