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

Shading Areas in Matplotlib

Learn how to shade areas between curves, highlight selected regions, and display important ranges in Matplotlib charts. Explore fill_between(), fill(), axvspan(), and axhspan() with practical examples.

1. Learning Objectives

After completing this lesson, you will be able to:

  • Understand area shading in Matplotlib.
  • Use plt.fill_between() to shade areas between curves.
  • Use plt.fill() to fill areas inside polygons.
  • Use axvspan() to highlight vertical regions.
  • Use axhspan() to highlight horizontal regions.
  • Customize shading colours and transparency.
  • Apply conditional shading using the where parameter.
  • Understand interpolation and step-based shading.
  • Highlight important ranges in real-world charts.

2. Introduction to Shading Areas

Shading is used to highlight a particular area or range inside a chart. It makes important information easier to identify and understand.

For example, we can shade the area between two lines, highlight a specific time period, display a target range, or show regions where values are above or below a threshold.

Why do we use shading?

  • To highlight important chart regions.
  • To compare two data series.
  • To display safe and warning ranges.
  • To show areas above or below a threshold.
  • To make charts more informative.
Upper Curve Lower Curve Shaded Region X Axis Y Axis

Shading can visually represent the area between two curves.

3. Using fill_between()

The fill_between() function fills the area between two horizontal curves. It is commonly used with line charts to highlight the difference or range between two data series.

Basic syntax:

plt.fill_between(
    x,
    y1,
    y2=0,
    color=None,
    alpha=None
)

Important arguments:

  • x: X-axis coordinates.
  • y1: First boundary values.
  • y2: Second boundary values. The default is 0.
  • color: Shading colour.
  • alpha: Transparency level.

Example: Shading under a line

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]

plt.plot(x, y, color="blue", marker="o")

plt.fill_between(
    x,
    y,
    0,
    color="skyblue",
    alpha=0.4
)

plt.title("Shading Under a Line")
plt.xlabel("X Values")
plt.ylabel("Y Values")

plt.show()

Output

A line chart is displayed.

The line connects five data points.
A transparent sky-blue area is filled
between the line and Y = 0.

Title: Shading Under a Line

Example: Shading between two curves

import matplotlib.pyplot as plt

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

y1 = [10, 20, 30, 25, 35]
y2 = [5, 10, 15, 20, 25]

plt.plot(x, y1, label="Upper Line")
plt.plot(x, y2, label="Lower Line")

plt.fill_between(
    x,
    y1,
    y2,
    color="lightgreen",
    alpha=0.5
)

plt.title("Area Between Two Lines")
plt.legend()

plt.show()

Output

Two line charts are displayed.

Upper Line: [10, 20, 30, 25, 35]
Lower Line: [5, 10, 15, 20, 25]

The area between both curves
is shaded with light green colour.
Tip: The fill_between() function is especially useful for comparing actual values with target values or showing the range between two measurements.

4. Conditional Shading Using where

The where parameter allows us to shade only selected sections of a chart based on a condition.

For example, we can shade only those areas where a data series is above a target value.

Example: Highlighting values above a target

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5, 6]
y = [10, 25, 20, 35, 40, 30]

target = 25

plt.plot(x, y, color="blue", marker="o")

plt.axhline(
    target,
    color="red",
    linestyle="--",
    label="Target"
)

plt.fill_between(
    x,
    y,
    target,
    where=[value >= target for value in y],
    color="green",
    alpha=0.3
)

plt.title("Conditional Shading")
plt.legend()

plt.show()

Output

A line chart is displayed with a red
dashed target line at Y = 25.

Only the portions where the data values
are above the target are shaded green.

Values above target:
25, 35, 40, 30
Target Above Target X Values

Conditional shading highlights only selected portions of a line.

Important: By default, where[i] controls the interval between adjacent X values. A single isolated True value may not produce a visible shaded interval. Use adjacent True values or interpolate=True when appropriate.

5. Understanding Interpolation

The interpolate parameter is useful when conditional shading is applied and two curves cross between data points.

When interpolate=True, Matplotlib calculates the intersection point between the curves so that the shaded region can end at the crossing point.

Example: Conditional shading with interpolation

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5, 6]
y1 = [10, 20, 30, 20, 15, 25]
y2 = [15, 15, 15, 15, 15, 15]

plt.plot(x, y1, label="Data")
plt.plot(x, y2, label="Threshold")

plt.fill_between(
    x,
    y1,
    y2,
    where=[a >= b for a, b in zip(y1, y2)],
    interpolate=True,
    color="orange",
    alpha=0.4
)

plt.title("Conditional Shading with Interpolation")
plt.legend()

plt.show()

Output

Two curves are displayed.

The area where the Data curve
is above the Threshold curve is shaded.

Interpolation helps the shaded boundary
meet the curve intersection points.
Tip: Use interpolation when the exact crossing point between two curves is important for your visualisation.

6. Using fill()

The fill() function is used to fill a polygon-shaped area created from a sequence of X and Y coordinates.

Unlike fill_between(), which fills between two boundaries, fill() creates a filled shape by connecting the supplied coordinate points.

Basic syntax:

plt.fill(
    x,
    y,
    color="blue",
    alpha=0.5
)

Example: Filling a polygon area

import matplotlib.pyplot as plt

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

plt.fill(
    x,
    y,
    color="lightblue",
    alpha=0.7,
    edgecolor="blue"
)

plt.title("Filled Polygon")
plt.xlabel("X Values")
plt.ylabel("Y Values")

plt.show()

Output

A filled polygon is displayed.

The polygon is created using
the supplied X and Y coordinates.

Fill colour: Light blue
Border colour: Blue
Transparency: 0.7

Example: Filling multiple regions

import matplotlib.pyplot as plt

x1 = [1, 2, 3, 2]
y1 = [1, 3, 3, 1]

x2 = [4, 5, 6, 5]
y2 = [1, 3, 3, 1]

plt.fill(x1, y1, color="skyblue", alpha=0.7)
plt.fill(x2, y2, color="lightgreen", alpha=0.7)

plt.title("Multiple Filled Areas")

plt.show()

Output

Two separate filled polygon regions
are displayed in the same figure.

First region: Sky blue
Second region: Light green
Remember: Use fill() for custom polygon areas and fill_between() for shading between two curves.

7. Using axvspan()

The axvspan() function highlights a vertical region between two X-axis positions.

It is useful for highlighting a particular time period, category range, or selected X-axis interval.

Basic syntax:

ax.axvspan(
    xmin,
    xmax,
    ymin=0,
    ymax=1,
    **kwargs
)

Important arguments:

  • xmin: Starting X position.
  • xmax: Ending X position.
  • ymin: Bottom boundary in axes coordinates.
  • ymax: Top boundary in axes coordinates.
  • color: Shading colour.
  • alpha: Transparency level.

Example: Highlighting a vertical region

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5, 6]
y = [10, 15, 20, 18, 30, 35]

fig, ax = plt.subplots()

ax.plot(x, y, marker="o")

ax.axvspan(
    3,
    5,
    color="yellow",
    alpha=0.3
)

ax.set_title("Vertical Shaded Region")
ax.set_xlabel("X Values")
ax.set_ylabel("Y Values")

plt.show()

Output

A line chart is displayed.

A transparent yellow vertical region
highlights the area between X = 3 and X = 5.

The plotted line remains visible
inside the highlighted region.
Highlighted Region X = 3 X = 5

axvspan() highlights a vertical interval across the axes.

Important: ymin and ymax in axvspan() use axes-relative coordinates from 0 to 1, not the chart's data Y values.

8. Using axhspan()

The axhspan() function highlights a horizontal region between two Y-axis positions.

It is useful for displaying target ranges, warning levels, safe zones, and threshold areas.

Basic syntax:

ax.axhspan(
    ymin,
    ymax,
    xmin=0,
    xmax=1,
    **kwargs
)

Important arguments:

  • ymin: Starting Y position.
  • ymax: Ending Y position.
  • xmin: Left boundary in axes coordinates.
  • xmax: Right boundary in axes coordinates.
  • color: Shading colour.
  • alpha: Transparency level.

Example: Highlighting a horizontal range

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5, 6]
y = [10, 20, 15, 30, 25, 35]

fig, ax = plt.subplots()

ax.plot(x, y, marker="o")

ax.axhspan(
    15,
    25,
    color="lightgreen",
    alpha=0.4
)

ax.set_title("Horizontal Shaded Region")
ax.set_xlabel("X Values")
ax.set_ylabel("Y Values")

plt.show()

Output

A line chart is displayed.

A transparent green horizontal region
highlights values between Y = 15 and Y = 25.

The plotted line remains visible
inside the highlighted region.
Highlighted Range Upper Lower

axhspan() highlights a horizontal interval across the axes.

Tip: axhspan() is useful for displaying safe, warning, and danger ranges in monitoring charts.

9. Step-Based Shading

The step parameter in fill_between() controls how the filled region follows the data points.

Step Value Description
pre The step changes at the left side of each interval.
post The step changes at the right side of each interval.
mid The step changes at the midpoint of each interval.

Example: Step-based shading

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]

fig, ax = plt.subplots()

ax.step(x, y, where="post", color="blue")

ax.fill_between(
    x,
    y,
    0,
    step="post",
    color="skyblue",
    alpha=0.4
)

ax.set_title("Step-Based Shading")

plt.show()

Output

A step chart is displayed.

A sky-blue region is filled below
the step line down to Y = 0.

The shaded region follows
the post-step arrangement.
Practical Use: Step-based shading is useful for discrete values, state changes, and measurements that remain constant until the next observation.

10. Complete Practical Example: Sales Target Analysis

Let's create a sales chart where we compare actual sales with a target value. We will shade the regions above and below the target using different colours.

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]

actual_sales = [20, 35, 25, 45, 30, 50]
target_sales = [30, 30, 30, 30, 30, 30]

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

ax.plot(
    months,
    actual_sales,
    marker="o",
    color="blue",
    label="Actual Sales"
)

ax.plot(
    months,
    target_sales,
    color="red",
    linestyle="--",
    label="Target Sales"
)

ax.fill_between(
    range(len(months)),
    actual_sales,
    target_sales,
    where=[
        actual >= target
        for actual, target in zip(actual_sales, target_sales)
    ],
    interpolate=True,
    color="green",
    alpha=0.3,
    label="Above Target"
)

ax.fill_between(
    range(len(months)),
    actual_sales,
    target_sales,
    where=[
        actual < target
        for actual, target in zip(actual_sales, target_sales)
    ],
    interpolate=True,
    color="red",
    alpha=0.2,
    label="Below Target"
)

ax.set_xticks(range(len(months)))
ax.set_xticklabels(months)

ax.set_title("Monthly Sales Target Analysis")
ax.set_xlabel("Month")
ax.set_ylabel("Sales")

ax.legend()
ax.grid(True, linestyle="--", alpha=0.4)

plt.tight_layout()
plt.show()

Output

Monthly Sales Target Analysis

Months: Jan, Feb, Mar, Apr, May, Jun

Actual Sales:
20, 35, 25, 45, 30, 50

Target Sales:
30, 30, 30, 30, 30, 30

Green shading:
Regions where actual sales are above target.

Red shading:
Regions where actual sales are below target.

A dashed red line represents the target sales.
Practical Note: In this example, the X coordinates are numeric positions from 0 to 5. We use set_xticks() and set_xticklabels() to display the month names.

11. Comparison of Shading Functions

Function Purpose Typical Use
fill_between() Fills the area between two curves. Comparing two data series.
fill() Fills a polygon area. Custom filled shapes.
axvspan() Highlights a vertical region. Selected X-axis interval.
axhspan() Highlights a horizontal region. Target or warning range.

12. Important Shading Parameters

Parameter Purpose Example
color Sets the shading colour. color="lightblue"
alpha Controls transparency. alpha=0.4
where Applies conditional shading. where=y > 20
interpolate Calculates crossing boundaries for conditional shading. interpolate=True
step Controls step-based shading. step="post"
facecolor Sets the interior colour of filled shapes. facecolor="yellow"
edgecolor Sets the boundary colour. edgecolor="blue"

13. Practical Activity

Activity: Temperature Range Analysis

Create a temperature chart and highlight the normal, warning, and high-temperature ranges.

Given data:

days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

temperature = [25, 28, 32, 35, 30, 38, 27]

Your tasks:

  1. Create a line chart using the temperature data.
  2. Set the chart title to Weekly Temperature Analysis.
  3. Use axhspan() to highlight the normal range.
  4. Use another axhspan() for the warning range.
  5. Use fill_between() to shade the area below the temperature curve.
  6. Use different colours for each range.
  7. Set suitable transparency using the alpha parameter.
  8. Add a legend and axis labels.

14. Practice Questions

  1. What is shading in Matplotlib?
  2. What is the purpose of fill_between()?
  3. What is the difference between fill() and fill_between()?
  4. How can you shade an area between two curves?
  5. What is the purpose of the where parameter?
  6. Why do we use interpolate=True?
  7. What is the difference between axvspan() and axhspan()?
  8. What is the purpose of the alpha parameter?
  9. What are the available step options in fill_between()?
  10. How can you highlight values above a target?
  11. Why is shading useful in data visualisation?

Summary

In this lesson, we learned how to shade areas in Matplotlib charts. We explored fill_between() to fill areas below a curve and between two curves. We also learned how to use conditional shading with the where parameter.

We understood interpolation and step-based shading, which help control how filled regions are displayed around data points and curve intersections.

We also learned how to use fill() for polygon areas, axvspan() for vertical regions, and axhspan() for horizontal ranges. We customized shading using colours and transparency.

Finally, we created a practical sales target analysis chart that highlights values above and below a target. With this lesson, the Annotations and Shapes section is complete. In the next section, we will explore Matplotlib styles and themes.