Add error bars to a Matplotlib bar plot
Last Updated :
01 May, 2025
Improve
In this article, we will create a bar plot with error bars using Matplotlib. Error bar charts are a great way to represent the variability in your data. It can be applied to graphs to provide an additional layer of detailed information on the presented data.
Approach:
- Import the required Python library
- Making simple data
- Plot using the plt.errorbar() function
- Display graph
The errorbar() function in the pyplot module of the matplotlib library plots data points of y versus x with optional error bars, either as lines, markers, or both.
Syntax for the Function
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
)
Description of Parameters
- x, y: Horizontal and vertical coordinates of the data points (required).
- yerr, xerr: Errors for the y and x coordinates, can be a single value or an array.
- fmt: Format for the markers (e.g. 'o', 's', 'b-'). Default is ''.
- ecolor: Color of the error bars. Default is None (uses the current axis color).
- elinewidth: Line width of error bars. Default is None (default line width).
- capsize: Length of the caps at the ends of the error bars. Default is None.
- barsabove: If True, error bars are drawn above the plot symbols. Default is False.
- lolims, uplims, xlolims, xuplims: Limit error bars to certain regions. Default is False for all.
- errorevery: Frequency of error bars (default is 1, for all points).
- capthick: Thickness of the cap lines. Default is None.
- data: Data object (e.g. pandas DataFrame) to use.
- kwargs: Additional keyword arguments for customizing properties.
Implementing Error bars in Python
Example 1: Adding some errors in a 'y' value
import matplotlib.pyplot as plt
x = [1, 3, 5, 7]
y = [11, 2, 4, 19]
c = [1, 3, 2, 1]
plt.bar(x, y)
plt.errorbar(x, y, yerr=c, fmt="o", color="r")
plt.show()
Output:
Example 2: Adding Some errors in the 'x' value
import matplotlib.pyplot as plt
x = [1, 3, 5, 7]
y = [11, 2, 4, 19]
c = [1, 3, 2, 1]
plt.bar(x, y)
plt.errorbar(x, y, xerr=c, fmt="o", color="r")
plt.show()
Output:
Example 3: Adding error in x and y
import matplotlib.pyplot as plt
x = [1, 3, 5, 7]
y = [11, 2, 4, 19]
c = [1, 3, 2, 1]
d = [1, 3, 2, 1]
plt.bar(x, y)
plt.errorbar(x, y, 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]
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]
plt.bar(x, y)
plt.errorbar(x, y, yerr=y_error,
xerr=x_error, fmt='o', color="r")
plt.show()
Output: