在 Matplotlib 中为误差线添加垂直上限
先决条件: Matplotlib
matplotlib 库的 pyplot 模块中的errorbar()函数用于将 y 与 x 绘制为带有附加误差条的线条和/或标记。对于我们的需求,我们需要特别关注这个函数的 capsize 属性。简单地为它提供一个值将产生我们所需的功能。
Syntax: matplotlib.pyplot.errorbar(x, y, yerr=None, xerr=None, fmt=”, ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, \*, data=None, \*\*kwargs)
Parameters: This method accept the following parameters that are described below:
- x, y: These parameters are the horizontal and vertical coordinates of the data points.
- fmt: This parameter is an optional parameter and it contains the string value.
- capsize: This parameter is also an optional parameter. And it is the length of the error bar caps in points with default value NONE.
- barsabove: This parameter is also an optional parameter. It contains boolean value True for plotting errorsbars above the plot symbols.Its default value is False.
- errorevery: This parameter is also an optional parameter. They contain integer values which is used to draw error bars on a subset of the data.
方法
- 导入模块
- 创建数据
- 提供错误值
- 将所有值与 capsize 属性及其值一起传递给 errorbar()函数
- 显示图
示例 1:
Python3
import matplotlib.pyplot as plt
x_values = [5, 4, 3, 2, 1]
y_values = [8, 4, 9, 1, 0]
y_error = [0, 0.3, 1, 0.2, 0.75]
plt.errorbar(x_values, y_values, yerr=y_error,
fmt='o', markersize=8, capsize=10)
plt.show()
Python3
import matplotlib.pyplot as plt
x_values = [0, 1, 2, 3, 4, 5]
y_values = [8, 4, 9, 1, 0, 5]
plt.plot(x_values, y_values)
x_error = [0, 0.3, 1, 0.2, 0.75, 2]
plt.errorbar(x_values, y_values, xerr=x_error,
fmt='o', markersize=8, capsize=6, color="r")
plt.show()
Python3
import matplotlib.pyplot as plt
x_values = [0, 1, 2, 3, 4, 5]
y_values = [8, 4, 9, 1, 0, 5]
x_error = [0, 0.3, 1, 0.2, 0.75, 2]
y_error = [0.3, 0.3, 2, 0.5, 0.7, 0.6]
plt.errorbar(x_values, y_values, xerr=x_error, yerr=y_error,
fmt='D', markersize=8, capsize=3, color="r")
plt.show()
输出:
示例 2:
蟒蛇3
import matplotlib.pyplot as plt
x_values = [0, 1, 2, 3, 4, 5]
y_values = [8, 4, 9, 1, 0, 5]
plt.plot(x_values, y_values)
x_error = [0, 0.3, 1, 0.2, 0.75, 2]
plt.errorbar(x_values, y_values, xerr=x_error,
fmt='o', markersize=8, capsize=6, color="r")
plt.show()
输出:
示例 3:
蟒蛇3
import matplotlib.pyplot as plt
x_values = [0, 1, 2, 3, 4, 5]
y_values = [8, 4, 9, 1, 0, 5]
x_error = [0, 0.3, 1, 0.2, 0.75, 2]
y_error = [0.3, 0.3, 2, 0.5, 0.7, 0.6]
plt.errorbar(x_values, y_values, xerr=x_error, yerr=y_error,
fmt='D', markersize=8, capsize=3, color="r")
plt.show()
输出: