Make logically shading region for a curve in matplotlib

To make logically shading region for a curve in matplotlib, we can use BrokenBarHCollection.span_where() to create conditional shading based on the curve's values. This technique is useful for highlighting regions where a function satisfies certain conditions.

Steps

  • Set the figure size and adjust the padding between and around the subplots.

  • Create t, s1 and s2 data points using numpy.

  • Create a figure and a set of subplots.

  • Plot t and s1 data points; add a horizontal line across the axis.

  • Create a collection of horizontal bars spanning yrange with a sequence of xranges.

  • Add a Collection to the axes' collections; return the collection.

  • To display the figure, use show() method.

Example

Here's how to shade regions where a sine curve is positive (green) and negative (red) ?

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.collections as collections

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

t = np.arange(0.0, 2, 0.01)
s1 = np.sin(2 * np.pi * t)
s2 = 1.2 * np.sin(4 * np.pi * t)

fig, ax = plt.subplots()

ax.plot(t, s1, color='black')
ax.axhline(0, color='black', lw=2)

collection = collections.BrokenBarHCollection.span_where(t, ymin=0, ymax=1,
    where=s1 > 0, facecolor='green', alpha=0.5
)
ax.add_collection(collection)

collection = collections.BrokenBarHCollection.span_where( t, ymin=-1, ymax=0,
    where=s1 < 0, facecolor='red', alpha=0.5
)
ax.add_collection(collection)

plt.show()

Output

The output shows a sine wave with green shading above the x-axis (where s1 > 0) and red shading below (where s1 Conditional Shading Based on Curve Values 0 1 -1

Key Parameters

  • where − Boolean condition for shading

  • ymin, ymax − Vertical extent of shading

  • facecolor − Color of the shaded region

  • alpha − Transparency level (0-1)

Conclusion

Use BrokenBarHCollection.span_where() to create conditional shading regions in matplotlib. This method allows you to highlight specific areas where your curve meets certain logical conditions, making data visualization more informative.

Updated on: 2026-03-26T15:05:38+05:30

253 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements