Master Matplotlib From Scratch

Learn Matplotlib fundamentals, figure anatomy, basic plotting, chart customization, subplots, statistical visualizations, color mapping, annotations, 3D plotting, animations, and interactive visualizations through structured practical lessons.

COURSE SYLLABUS
1. Introduction & Environment Setup
What is Matplotlib? Installation Environment Setup Imports and Conventions
2. Core Figure Anatomy & Structures
Figure vs Axes Creating Canvas Dimensions and Resolution Saving Visuals
3. Basic Plotting
Line Plots Scatter Plots Bar Charts Histograms
4. Basic Visual Formatting & Labels
Titles and Labels Text Customization Legends Grid Lines
5. Advanced Plot Customization
Format Strings Line and Marker Styling Color Systems Transparency
6. Axis Control, Ticks & Limits
Axis Limits Custom Ticks Tick Labels Axis Scaling
7. Multi-Plot Layouts & Subplots
Basic Subplots Indexing Subplots Layout Tuning Advanced Grids
8. Advanced Statistical & Data-Specific Plots
Pie Charts Box and Whisker Plots Violin Plots Error Bars
9. Color Mapping & 2D Data Visualizations
Colormaps Heatmaps and Images Colorbars Contour Plots
10. Annotations & Shapes
Basic Text Smart Annotations Drawing Shapes Shading Areas
11. Customizing Styles & Themes
Built-in Styles Custom Style Sheets Global Configurations
12. Object-Oriented API vs Pyplot
Pyplot vs Object-Oriented API Transitioning Methods Dual Axis Plots
13. Deep Integration with Pandas & Seaborn
Pandas Plotting Backend Seaborn Overlays Passing Axes
14. 3D Plotting
3D Setup 3D Lines and Scatter Surface and Wireframes Camera View
15. Dynamic & Live Plots
Interactive Mode Animation Module Real-time Updates Exporting Animations
16. Performance Optimization & Interactive Backends
Plotting Speed Interactive Backends Event Handling

Error Bars in Matplotlib

Learn how to display uncertainty and variation in data using Matplotlib error bars. Understand x-error, y-error, symmetric and asymmetric errors, caps, styling and practical examples.

1. Learning Objectives

After completing this lesson, you will be able to:

  • Understand what error bars are.
  • Understand uncertainty and variation in data.
  • Create error bars using Matplotlib.
  • Display vertical and horizontal error bars.
  • Customize error bar colours and line widths.
  • Control error bar caps and markers.
  • Create asymmetric error bars.
  • Display error bars with line and scatter plots.
  • Understand common error bar parameters.

2. Introduction to Error Bars

Error bars are graphical indicators used to show the uncertainty, variability or possible error associated with numerical measurements.

They are commonly displayed around data points in charts. Error bars help users understand how much a measured value may vary or how uncertain an estimate may be.

Real-Life Example

Suppose a researcher measures the average temperature of a city over five days. Each daily average may have some variation. Error bars can show the range of uncertainty or variation around each average.

Day 1 Day 2 Day 3 Day 4 Understanding Error Bars

Conceptual illustration showing data points with vertical error ranges.

3. Why Do We Use Error Bars?

A chart without error bars displays the measured values but may not show how much uncertainty or variation exists around those values.

Error bars provide additional information and help users interpret the reliability and spread of measurements.

Common Applications

  • Scientific experiments and research.
  • Medical and laboratory measurements.
  • Temperature and weather observations.
  • Business performance comparisons.
  • Statistical analysis and data science.
  • Machine learning model evaluation.
Remember: Error bars do not automatically mean that the data is incorrect. They represent a defined measure of uncertainty or variability.

4. Types of Error Bars

Matplotlib supports different types of error bars depending on the dimension and the type of uncertainty being displayed.

Vertical Error Bars

Vertical error bars show uncertainty in the Y-axis values. They are useful when displaying measurement variation around a plotted value.

Horizontal Error Bars

Horizontal error bars show uncertainty in the X-axis values. They are useful when the independent variable also has measurement uncertainty.

Both X and Y Error Bars

You can display both horizontal and vertical uncertainty around a point by providing both xerr and yerr.

Y Error X Error X and Y Error Bars Centre point represents the measured value

Conceptual diagram showing horizontal and vertical error bars around a data point.

5. Import Matplotlib and NumPy

Before creating error bars, import Matplotlib's pyplot module. NumPy can be used to prepare numerical data.

import matplotlib.pyplot as plt
import numpy as np

Matplotlib provides the plt.errorbar() function to create charts with error bars.

6. Creating Basic Error Bars

The simplest way to create error bars is to provide X values, Y values and the uncertainty in Y values.

Example

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

y = [10, 15, 13, 18, 20]

y_error = [1, 2, 1, 3, 2]

plt.errorbar(
    x,
    y,
    yerr=y_error
)

plt.title("Basic Error Bar Chart")
plt.xlabel("X Values")
plt.ylabel("Y Values")

plt.show()

Expected Output

Basic Error Bar Chart

Five data points are displayed.

Each point has a vertical error bar:
Point 1 = Error 1
Point 2 = Error 2
Point 3 = Error 1
Point 4 = Error 3
Point 5 = Error 2
Tip: The yerr parameter specifies the error magnitude around each Y value.

7. Creating Vertical Error Bars

Vertical error bars are created by using the yerr parameter. They show the uncertainty above and below each plotted Y value.

import matplotlib.pyplot as plt

days = [1, 2, 3, 4, 5]

temperature = [25, 28, 27, 30, 29]

temperature_error = [2, 1, 3, 2, 1]

plt.errorbar(
    days,
    temperature,
    yerr=temperature_error,
    fmt="o"
)

plt.title("Daily Temperature with Error Bars")
plt.xlabel("Day")
plt.ylabel("Temperature")

plt.show()

Expected Output

Daily Temperature with Error Bars

Five temperature measurements are displayed.
Each measurement has a vertical error range.

Day 1 = 25 ± 2
Day 2 = 28 ± 1
Day 3 = 27 ± 3
Day 4 = 30 ± 2
Day 5 = 29 ± 1

8. Creating Horizontal Error Bars

Use the xerr parameter to display horizontal error bars. These bars represent uncertainty in the X values.

import matplotlib.pyplot as plt

x = [10, 20, 30, 40, 50]

y = [5, 8, 7, 10, 12]

x_error = [2, 3, 1, 4, 2]

plt.errorbar(
    x,
    y,
    xerr=x_error,
    fmt="o"
)

plt.title("Horizontal Error Bars")
plt.xlabel("X Values")
plt.ylabel("Y Values")

plt.show()

Expected Output

Horizontal Error Bars

Five data points are displayed.
Each point has a horizontal error range.

X Error Values:
2, 3, 1, 4, 2

9. Displaying Both X and Y Error Bars

Matplotlib allows you to display horizontal and vertical error bars together. Provide values for both xerr and yerr.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

y = [10, 15, 13, 18, 20]

x_error = [0.2, 0.3, 0.2, 0.4, 0.3]

y_error = [1, 2, 1, 3, 2]

plt.errorbar(
    x,
    y,
    xerr=x_error,
    yerr=y_error,
    fmt="o"
)

plt.title("X and Y Error Bars")
plt.xlabel("X Values")
plt.ylabel("Y Values")

plt.show()

Expected Output

X and Y Error Bars

Five data points are displayed.

Each point contains:
- Horizontal error range
- Vertical error range
- Central data marker

10. Error Bars with Connecting Lines

You can connect data points using a line while displaying error bars. The fmt parameter controls the marker and line format.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

y = [10, 15, 13, 18, 20]

y_error = [1, 2, 1, 3, 2]

plt.errorbar(
    x,
    y,
    yerr=y_error,
    fmt="o-"
)

plt.title("Line Plot with Error Bars")
plt.xlabel("X Values")
plt.ylabel("Y Values")

plt.show()

Expected Output

Line Plot with Error Bars

Data points are connected by a line.
Each data point displays a vertical error bar.
Tip: The format o- displays circular markers connected by solid lines.

11. Adding Caps to Error Bars

Caps are small horizontal or vertical lines at the ends of error bars. The capsize parameter controls their size.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

y = [10, 15, 13, 18, 20]

y_error = [1, 2, 1, 3, 2]

plt.errorbar(
    x,
    y,
    yerr=y_error,
    fmt="o",
    capsize=8
)

plt.title("Error Bars with Caps")
plt.xlabel("X Values")
plt.ylabel("Y Values")

plt.show()

Expected Output

Error Bars with Caps

Five data points are displayed.
Each vertical error bar has visible end caps.
The cap size is set to 8 points.
Remember: A larger capsize creates longer cap lines at the ends of the error bars.

12. Customizing Error Bar Colours and Width

You can customize error bars using parameters such as ecolor, elinewidth and capthick.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

y = [10, 15, 13, 18, 20]

y_error = [1, 2, 1, 3, 2]

plt.errorbar(
    x,
    y,
    yerr=y_error,
    fmt="o",
    color="blue",
    ecolor="red",
    elinewidth=2,
    capsize=6,
    capthick=2
)

plt.title("Customized Error Bars")
plt.xlabel("X Values")
plt.ylabel("Y Values")

plt.show()

Expected Output

Customized Error Bars

Data Markers and Line = Blue
Error Bars             = Red
Error Bar Width        = 2
Cap Size               = 6
Cap Thickness          = 2
Parameter Purpose
color Sets the data line and marker colour.
ecolor Sets the error bar colour.
elinewidth Controls error bar line thickness.
capsize Controls the length of error bar caps.
capthick Controls the thickness of cap lines.

13. Creating Asymmetric Error Bars

Symmetric error bars have the same error magnitude above and below the measured value. Asymmetric error bars use different lower and upper error magnitudes.

Matplotlib accepts a two-row error array. The first row contains lower errors, and the second row contains upper errors.

import matplotlib.pyplot as plt
import numpy as np

x = [1, 2, 3, 4]

y = [10, 15, 13, 18]

lower_error = [1, 2, 1, 2]

upper_error = [3, 4, 2, 5]

asymmetric_error = np.array([
    lower_error,
    upper_error
])

plt.errorbar(
    x,
    y,
    yerr=asymmetric_error,
    fmt="o",
    capsize=5
)

plt.title("Asymmetric Error Bars")
plt.xlabel("X Values")
plt.ylabel("Y Values")

plt.show()

Expected Output

Asymmetric Error Bars

Point 1 = Lower Error 1, Upper Error 3
Point 2 = Lower Error 2, Upper Error 4
Point 3 = Lower Error 1, Upper Error 2
Point 4 = Lower Error 2, Upper Error 5

Upper and lower error lengths are different.
Tip: Asymmetric errors are useful when uncertainty is not equal in both directions.

14. Displaying Error Bars Above Data Markers

The barsabove parameter controls whether error bars are drawn above the data markers and lines.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]

y = [10, 15, 13, 18]

y_error = [2, 3, 1, 2]

plt.errorbar(
    x,
    y,
    yerr=y_error,
    fmt="o-",
    barsabove=True,
    capsize=5
)

plt.title("Error Bars Above Data Markers")

plt.xlabel("X Values")
plt.ylabel("Y Values")

plt.show()

Expected Output

Error Bars Above Data Markers

A line plot is displayed.
Error bar lines are drawn above the data markers
and connecting line.

15. Displaying Error Bars at Selected Points

The errorevery parameter controls how often error bars are displayed. It is useful when a chart contains many data points.

import matplotlib.pyplot as plt

x = list(range(1, 11))

y = [10, 12, 14, 13, 16, 18, 17, 20, 22, 21]

y_error = [1] * 10

plt.errorbar(
    x,
    y,
    yerr=y_error,
    fmt="o-",
    errorevery=2,
    capsize=4
)

plt.title("Selected Error Bars")
plt.xlabel("X Values")
plt.ylabel("Y Values")

plt.show()

Expected Output

Selected Error Bars

Ten data points are connected by a line.
Error bars are displayed at every second point.
Remember: The errorevery parameter changes which points display error bars. It does not remove the other data points.

16. Displaying Error Limits with lolims and uplims

Matplotlib provides parameters such as lolims and uplims to indicate that a value represents a lower or upper limit.

Lower Limit Example

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]

y = [10, 15, 13, 18]

y_error = [2, 2, 2, 2]

plt.errorbar(
    x,
    y,
    yerr=y_error,
    fmt="o",
    lolims=True,
    capsize=5
)

plt.title("Lower Limit Error Bars")
plt.xlabel("X Values")
plt.ylabel("Y Values")

plt.show()

Expected Output

Lower Limit Error Bars

The chart displays lower-limit indicators
at the specified data points.

Upper Limit Example

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]

y = [10, 15, 13, 18]

y_error = [2, 2, 2, 2]

plt.errorbar(
    x,
    y,
    yerr=y_error,
    fmt="o",
    uplims=True,
    capsize=5
)

plt.title("Upper Limit Error Bars")
plt.xlabel("X Values")
plt.ylabel("Y Values")

plt.show()

Expected Output

Upper Limit Error Bars

The chart displays upper-limit indicators
at the specified data points.
Important: Limit indicators have specific statistical meaning. Use them only when the data genuinely represents a one-sided bound or limit.

17. Combining Scatter Plots with Error Bars

Error bars can be displayed with scatter-style markers. Set the marker format using the fmt parameter.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

y = [12, 18, 15, 22, 25]

y_error = [2, 1, 3, 2, 1]

plt.errorbar(
    x,
    y,
    yerr=y_error,
    fmt="s",
    color="purple",
    ecolor="orange",
    capsize=5
)

plt.title("Scatter Plot with Error Bars")
plt.xlabel("X Values")
plt.ylabel("Y Values")

plt.show()

Expected Output

Scatter Plot with Error Bars

Square markers represent the data points.
Orange vertical bars represent uncertainty.
Caps are visible at the ends of the error bars.

18. Error Bars Using the Object-Oriented API

The object-oriented approach provides better control over the figure and axes. Instead of using plt.errorbar(), create a Figure and Axes object and call ax.errorbar().

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

y = [10, 15, 13, 18, 20]

y_error = [1, 2, 1, 3, 2]

fig, ax = plt.subplots(figsize=(8, 5))

ax.errorbar(
    x,
    y,
    yerr=y_error,
    fmt="o-",
    capsize=6,
    color="blue",
    ecolor="red"
)

ax.set_title("Error Bars Using Axes")
ax.set_xlabel("X Values")
ax.set_ylabel("Y Values")

ax.grid(True, alpha=0.3)

plt.show()

Expected Output

Error Bars Using Axes

A line chart with error bars is displayed.
The data line is blue.
The error bars are red.
The chart includes a grid.
Tip: The object-oriented API is useful when working with multiple subplots and complex figures.

19. Important Parameters of plt.errorbar()

Parameter Description Example
x Horizontal data values. x=[1, 2, 3]
y Vertical data values. y=[10, 15, 20]
xerr Horizontal error magnitudes. xerr=2
yerr Vertical error magnitudes. yerr=1
fmt Controls marker and line format. fmt="o-"
ecolor Sets error bar colour. ecolor="red"
elinewidth Controls error line thickness. elinewidth=2
capsize Controls error bar cap size. capsize=5
capthick Controls cap line thickness. capthick=2
barsabove Draws error bars above data markers. barsabove=True
errorevery Controls which points display error bars. errorevery=2
lolims Indicates lower-limit values. lolims=True
uplims Indicates upper-limit values. uplims=True
solid_capstyle Controls the cap style for solid error lines. solid_capstyle="projecting"

20. Practical Example: Monthly Temperature Measurements

Let's create a chart showing the average temperature recorded over six months. Each measurement includes an uncertainty range.

Complete Python Program

import matplotlib.pyplot as plt
import numpy as np

months = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June"
]

temperature = [22, 24, 28, 32, 35, 34]

temperature_error = [2, 1, 3, 2, 2, 1]

x = np.arange(len(months))

fig, ax = plt.subplots(figsize=(9, 6))

ax.errorbar(
    x,
    temperature,
    yerr=temperature_error,
    fmt="o-",
    color="#2563eb",
    ecolor="#dc2626",
    elinewidth=2,
    capsize=6,
    capthick=2,
    markersize=7
)

ax.set_xticks(x)
ax.set_xticklabels(months)

ax.set_title("Monthly Average Temperature")
ax.set_xlabel("Months")
ax.set_ylabel("Temperature (°C)")

ax.grid(axis="y", linestyle="--", alpha=0.4)

plt.show()

Expected Output

Monthly Average Temperature

January   : 22 ± 2 °C
February  : 24 ± 1 °C
March     : 28 ± 3 °C
April     : 32 ± 2 °C
May       : 35 ± 2 °C
June      : 34 ± 1 °C

A line chart displays the average temperatures.
Each point includes vertical uncertainty bars.

Understanding the Result

The chart displays the average temperature for each month. The error bars show the specified uncertainty around each average measurement. March has a larger uncertainty range than February and June.

21. Common Statistical Measures Used for Error Bars

Error bars can represent different statistical quantities. It is important to understand what the error values mean before interpreting a chart.

Measure Meaning
Standard Deviation Measures the spread of individual observations around the mean.
Standard Error Measures the estimated variability of a sample mean.
Confidence Interval Provides an interval calculated using a specified confidence procedure.
Measurement Uncertainty Represents uncertainty associated with a measurement.
Important: Matplotlib only draws the error values you provide. It does not automatically determine whether those values represent standard deviation, standard error or confidence intervals.

22. Best Practices for Error Bars

  • Clearly explain what the error bars represent.
  • Use suitable error values for your dataset.
  • Choose colours that contrast with the data markers.
  • Use caps when they improve readability.
  • Avoid displaying too many overlapping error bars.
  • Use asymmetric error bars when uncertainty is unequal.
  • Keep axis labels and units clear.
  • Do not interpret overlapping error bars as a definitive statistical test.
Important: Overlap or non-overlap of error bars alone does not establish statistical significance. The interpretation depends on the type of interval and the statistical method used.

23. Common Mistakes and Solutions

Common Mistake Solution
Error array length does not match data. Provide compatible error values for each data point.
Negative error magnitudes are supplied. Use non-negative error magnitudes.
Horizontal error bars are missing. Use the xerr parameter.
Vertical error bars are missing. Use the yerr parameter.
Caps are not visible. Set a suitable capsize.
Asymmetric error shape is incorrect. Provide a two-row array containing lower and upper errors.
Error bars overlap too much. Use a suitable marker size and error display frequency.

24. Practice Questions

Beginner Level

  1. What are error bars?
  2. Which Matplotlib function creates error bars?
  3. What is the purpose of yerr?
  4. What is the purpose of xerr?
  5. What does capsize control?

Intermediate Level

  1. Explain the difference between horizontal and vertical error bars.
  2. What are symmetric and asymmetric error bars?
  3. What is the purpose of ecolor?
  4. Explain the use of errorevery.
  5. What is the purpose of barsabove?
  6. What is the difference between standard deviation and standard error?

Practical Tasks

  1. Create a basic chart with vertical error bars.
  2. Create a chart with horizontal error bars.
  3. Display both X and Y error bars.
  4. Customize error bar colours and cap sizes.
  5. Create asymmetric error bars.
  6. Create a monthly temperature chart with uncertainty.

Summary

Error bars are graphical indicators used to display uncertainty or variation around measured data values. They help users understand the possible range around individual observations or estimates.

Matplotlib provides the plt.errorbar() function to create error bars. The xerr parameter displays horizontal uncertainty, while yerr displays vertical uncertainty. Both parameters can be used together.

Error bars can be customized using parameters such as fmt, ecolor, elinewidth, capsize and capthick. Matplotlib also supports asymmetric errors, selected error display positions and one-sided limit indicators.

Error bars are commonly used in scientific research, experiments, business analysis and statistical visualization. Always explain whether the displayed uncertainty represents standard deviation, standard error, a confidence interval or another measurement.