0
0
Matplotlibdata~5 mins

Error bars on bar charts in Matplotlib

Choose your learning style9 modes available
Introduction

Error bars show how much the data might vary. They help us see the uncertainty or spread in the data on bar charts.

When you want to show the average sales per month with possible variation.
When comparing test scores of different groups and showing the range of scores.
When displaying survey results with confidence intervals.
When showing measurements with possible errors in experiments.
Syntax
Matplotlib
plt.bar(x, height, yerr=error, capsize=5)

# x: positions of bars
# height: values for bars
# yerr: error values for bars
# capsize: length of error bar caps

yerr can be a single value, list, or array showing error size.

capsize controls the horizontal line length at the top of error bars.

Examples
Basic bar chart with different error sizes for each bar.
Matplotlib
plt.bar([1, 2, 3], [10, 15, 7], yerr=[1, 2, 1])
Bar chart with same error size for all bars and longer caps.
Matplotlib
plt.bar([1, 2, 3], [10, 15, 7], yerr=2, capsize=10)
Bar chart with asymmetric error bars (different up and down errors).
Matplotlib
plt.bar([1, 2, 3], [10, 15, 7], yerr=[[1, 0.5, 1], [2, 1, 1.5]])
Sample Program

This code creates a bar chart with 4 bars. Each bar has an error bar showing the possible variation in scores.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

# Data
x = np.arange(4)
values = [20, 35, 30, 35]
errors = [2, 3, 4, 1]

# Create bar chart with error bars
plt.bar(x, values, yerr=errors, capsize=5, color='skyblue')

# Add labels and title
plt.xlabel('Groups')
plt.ylabel('Scores')
plt.title('Bar Chart with Error Bars')

# Show plot
plt.show()
OutputSuccess
Important Notes

Error bars help viewers understand the reliability of the data.

Make sure error values are positive numbers.

You can customize error bars with colors and line styles using extra parameters.

Summary

Error bars show uncertainty or variation on bar charts.

Use yerr to add error bars in plt.bar().

Customize error bars with capsize and other style options.