📜  将误差线添加到 Matplotlib 条形图

📅  最后修改于: 2022-05-13 01:55:44.623000             🧑  作者: Mango

将误差线添加到 Matplotlib 条形图

先决条件: Matplotlib

在本文中,我们将使用 Matplotlib 创建带有误差线的条形图。误差条形图是表示数据可变性的好方法。它可以应用于图形以提供有关所呈现数据的详细信息的附加层。

方法:

  • 导入所需的Python库。
  • 制作简单的数据。
  • 使用 plt.errorbar()函数绘图
  • 显示图表

错误栏 matplotlib 库的 pyplot 模块中的函数用于将 y 与 x 绘制为带有附加误差条的线条和/或标记

下面给出使用上述方法的实现:

示例 1:在“y”值中添加一些错误。

Python3
# importing matplotlib
import matplotlib.pyplot as plt
  
# making a simple plot
a = [1, 3, 5, 7]
b = [11, 2, 4, 19]
  
# Plot scatter here
plt.bar(a, b)
  
c = [1, 3, 2, 1]
  
plt.errorbar(a, b, yerr=c, fmt="o", color="r")
  
plt.show()


Python3
# importing matplotlib
import matplotlib.pyplot as plt
  
# making a simple plot
a = [1, 3, 5, 7]
b = [11, 2, 4, 19]
  
# Plot scatter here
plt.bar(a, b)
  
c = [1, 3, 2, 1]
  
plt.errorbar(a, b, xerr=c, fmt="o", color="r")
  
plt.show()


Python3
import matplotlib.pyplot as plt
  
a = [1, 3, 5, 7]
b = [11, 2, 4, 19]
  
plt.bar(a, b)
  
c = [1, 3, 2, 1]
d = [1, 3, 2, 1]
  
plt.errorbar(a, b, xerr=c, yerr=d, fmt="o", color="r")
plt.show()


Python3
# importing matplotlib
import matplotlib.pyplot as plt
  
# making a simple plot
x = [1, 2, 3, 4, 5]
y = [1, 2, 1, 2, 1]
  
# creating error
y_errormin = [0.1, 0.5, 0.9, 0.1, 0.9]
y_errormax = [0.2, 0.4, 0.6,  0.4, 0.2]
  
x_error = 0.5
  
y_error = [y_errormin, y_errormax]
  
# ploting graph
plt.bar(x, y)
  
plt.errorbar(x, y,
  
             yerr=y_error,
  
             xerr=x_error,
  
             fmt='o', color="r")  # you can use color ="r" for red or skip to default as blue
  
plt.show()


输出:

示例 2:在“x”值中添加一些错误。

蟒蛇3

# importing matplotlib
import matplotlib.pyplot as plt
  
# making a simple plot
a = [1, 3, 5, 7]
b = [11, 2, 4, 19]
  
# Plot scatter here
plt.bar(a, b)
  
c = [1, 3, 2, 1]
  
plt.errorbar(a, b, xerr=c, fmt="o", color="r")
  
plt.show()

输出:

示例 3:在 x 和 y 中添加错误

蟒蛇3

import matplotlib.pyplot as plt
  
a = [1, 3, 5, 7]
b = [11, 2, 4, 19]
  
plt.bar(a, b)
  
c = [1, 3, 2, 1]
d = [1, 3, 2, 1]
  
plt.errorbar(a, b, xerr=c, yerr=d, fmt="o", color="r")
plt.show()

输出:

示例 4:在 x 和 y 中添加变量误差。

蟒蛇3

# importing matplotlib
import matplotlib.pyplot as plt
  
# making a simple plot
x = [1, 2, 3, 4, 5]
y = [1, 2, 1, 2, 1]
  
# creating error
y_errormin = [0.1, 0.5, 0.9, 0.1, 0.9]
y_errormax = [0.2, 0.4, 0.6,  0.4, 0.2]
  
x_error = 0.5
  
y_error = [y_errormin, y_errormax]
  
# ploting graph
plt.bar(x, y)
  
plt.errorbar(x, y,
  
             yerr=y_error,
  
             xerr=x_error,
  
             fmt='o', color="r")  # you can use color ="r" for red or skip to default as blue
  
plt.show()

输出: