如何在误差线旁边添加误差值?

4
我正在使用matplotlib进行图表绘制。我已经准备好了plot和errorbar。我想在误差线旁边的文本中指定误差值。我希望得到这样的效果(在Pinta中编辑):enter image description here 是否有可能在这段代码中实现此功能:

import numpy as np
import matplotlib.pyplot as plt
import math

N = 8

y1 = [0.1532, 0.1861, 0.2618, 0.0584, 0.1839, 0.2049, 0.009, 0.2077]
y1err = []

for item in y1:
    err = 1.96*(math.sqrt(item*(1-item)/10000))
    y1err.append(err)

ind = np.arange(N)
width = 0.35

fig, ax = plt.subplots()

ax.bar(ind, y1, width, yerr=y1err, capsize=7)

ax.grid()
plt.show()

1个回答

4
您可以使用annotate函数在图表中添加文本标签。以下是实现的方法:
import numpy as np
import matplotlib.pyplot as plt
import math

N = 8

y1 = [0.1532, 0.1861, 0.2618, 0.0584, 0.1839, 0.2049, 0.009, 0.2077]
y1err = []

for item in y1:
    err = 1.96*(math.sqrt(item*(1-item)/10000))
    y1err.append(err)

ind = np.arange(N)
width = 0.35

fig, ax = plt.subplots()

ax.bar(ind, y1, width, yerr=y1err, capsize=7)

# add error values
for k, x in enumerate(ind):
    y = y1[k] + y1err[k]
    r = y1err[k] / y1[k] * 100
    ax.annotate(f'{y1[k]:.2f} +/- {r:.2f}%', (x, y), textcoords='offset points',
                xytext=(0, 3), ha='center', va='bottom', fontsize='x-small')

ax.grid()
plt.show()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接