如何在错误栏旁边添加错误值?
How to add error values next to error bars?
我正在使用 matplotlib 绘制绘图。我有情节和错误栏。我想在错误栏旁边的文本中指定错误值。我正在寻找这样的东西(在 pinta 中编辑):
是否可以在这段代码中做到这一点:
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()
您可以使用 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()
我正在使用 matplotlib 绘制绘图。我有情节和错误栏。我想在错误栏旁边的文本中指定错误值。我正在寻找这样的东西(在 pinta 中编辑):
是否可以在这段代码中做到这一点:
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()
您可以使用 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()