Use error bars in a Matplotlib scatter plot
Last Updated :
19 Apr, 2025
Improve
When visualizing data, error bars provide a great way to indicate variability or uncertainty in your measurements. In this article, we’ll explore how to create scatter plots with error bars using Matplotlib’s errorbar() function.
Syntax
matplotlib.pyplot.errorbar(
x, y,
yerr=None,
xerr=None,
fmt=”,
ecolor=None,
elinewidth=None,
capsize=None,
barsabove=False,
errorevery=1,
capthick=None,
**kwargs
)
Parameters:
- x, y: Coordinates of data points.
- xerr, yerr: Errors in the x or y directions.
- fmt: Format string for data points (e.g., ‘o’ for circles).
- ecolor: Color of error bars.
- capsize: Size of the cap on error bars.
- elinewidth: Line width of error bars.
Example 1: Adding Some error in a ‘y’ value.
import matplotlib.pyplot as plt
a = [1, 3, 5, 7]
b = [11, -2, 4, 19]
plt.scatter(a, b)
c = [1, 3, 2, 1]
plt.errorbar(a, b, yerr=c, fmt="o")
plt.show()
Output:
Example 2: Adding Some errors in the ‘x’ value.
import matplotlib.pyplot as plt
a = [1, 3, 5, 7]
b = [11, -2, 4, 19]
plt.scatter(a, b)
c = [1, 3, 2, 1]
plt.errorbar(a, b, xerr=c, fmt="o")
plt.show()
Output:
Example 3: Adding error in x & y
import matplotlib.pyplot as plt
a = [1, 3, 5, 7]
b = [11, -2, 4, 19]
plt.scatter(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()
Output:
Example 4: Adding variable error in x and y.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [1, 2, 1, 2, 1]
x_err = 0.5
y_err_min = [0.1, 0.5, 0.9, 0.1, 0.9]
y_err_max = [0.2, 0.4, 0.6, 0.4, 0.2]
# Asymmetric error bars
y_err = [y_err_min, y_err_max]
plt.errorbar(x, y, xerr=x_err, yerr=y_err, fmt='o')
plt.title("Asymmetric Error Bars")
plt.show()
Output:
Refer to Matplotlib for a better understanding.