Find the area between two curves plotted in Matplotlib

To find the area between two curves in Matplotlib, we use the fill_between() method. This is useful for visualizing the difference between datasets, confidence intervals, or regions of interest between mathematical functions.

Basic Example

Let's create two curves and fill the area between them ?

import matplotlib.pyplot as plt
import numpy as np

# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create data points
x = np.linspace(0, 1, 100)
curve1 = x ** 2  # Parabola
curve2 = x       # Linear function

# Plot the curves
plt.plot(x, curve1, label='y = x²')
plt.plot(x, curve2, label='y = x')

# Fill area between curves
plt.fill_between(x, curve1, curve2, color="grey", alpha=0.3, hatch='|')

# Add labels and legend
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.title('Area Between Two Curves')
plt.show()
x y y = x² y = x Area Between Two Curves

Filling Between Curve and Axis

You can also fill between a curve and the x-axis by omitting the second curve parameter ?

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)

plt.figure(figsize=(8, 4))
plt.plot(x, y, 'b-', linewidth=2, label='sin(x)')
plt.fill_between(x, y, alpha=0.3, color='blue')

plt.xlabel('x')
plt.ylabel('sin(x)')
plt.title('Area Under Sine Curve')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

Conditional Filling

Fill areas only where certain conditions are met using the where parameter ?

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-2, 2, 100)
y1 = x**2
y2 = 1

plt.figure(figsize=(8, 5))
plt.plot(x, y1, 'r-', label='y = x²')
plt.plot(x, y2, 'g-', label='y = 1')

# Fill where y1 < y2 (parabola below line)
plt.fill_between(x, y1, y2, where=(y1 < y2), 
                 color='green', alpha=0.3, label='x² < 1')

plt.xlabel('x')
plt.ylabel('y')
plt.title('Conditional Area Filling')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

Key Parameters

Parameter Description Example
color Fill color 'red', '#FF5733'
alpha Transparency (0-1) 0.3, 0.7
hatch Pattern style '|', '/', '\', '+'
where Condition for filling (y1 < y2)

Conclusion

Use fill_between() to highlight areas between curves or under functions. The where parameter allows conditional filling, while alpha and hatch provide visual customization options.

Updated on: 2026-03-25T21:30:45+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements