How to Create Fill Between Plot in Matplotlib: Simple Guide
Use the
fill_between function in matplotlib to fill the area between two curves or between a curve and a baseline. You provide the x-values and the y-values for the upper and lower boundaries, and matplotlib fills the space between them with color.Syntax
The basic syntax of fill_between is:
x: The x-coordinates of the points.y1: The y-coordinates of the first curve (lower boundary).y2(optional): The y-coordinates of the second curve (upper boundary). If omitted, the area is filled betweeny1and zero.color(optional): The fill color.alpha(optional): The transparency level of the fill.
python
matplotlib.pyplot.fill_between(x, y1, y2=None, color=None, alpha=None, **kwargs)
Example
This example shows how to fill the area between a sine curve and the x-axis.
python
import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2 * np.pi, 100) y = np.sin(x) plt.plot(x, y, label='sin(x)') plt.fill_between(x, y, color='skyblue', alpha=0.5) plt.title('Fill Between sin(x) and x-axis') plt.legend() plt.show()
Output
A plot showing the sine curve with the area between the curve and the x-axis filled in light blue.
Common Pitfalls
Common mistakes include:
- Not providing matching lengths for
x,y1, andy2. - Forgetting that if
y2is omitted, the fill is betweeny1and zero. - Using incompatible data types for coordinates.
Example of a common mistake and fix:
python
import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2 * np.pi, 100) y1 = np.sin(x) y2 = np.sin(x) + 1 # Wrong: y2 length mismatch (uncomment to see error) # y2_wrong = np.sin(x[:-1]) + 1 # plt.fill_between(x, y1, y2_wrong) # This will raise an error # Correct usage plt.plot(x, y1, label='sin(x)') plt.plot(x, y2, label='sin(x)+1') plt.fill_between(x, y1, y2, color='lightgreen', alpha=0.5) plt.legend() plt.title('Fill Between Two Curves') plt.show()
Output
A plot showing two sine-based curves with the area between them filled in light green.
Quick Reference
Tips for using fill_between:
- Use
alphato control transparency. - Use
whereparameter to fill conditionally. - Combine with
plotfor clear boundaries. - Colors can be named strings or hex codes.
Key Takeaways
Use matplotlib's fill_between to color the area between two curves or a curve and the x-axis.
Ensure x, y1, and y2 arrays have the same length to avoid errors.
The alpha parameter controls the transparency of the fill color.
You can fill conditionally using the where parameter for more control.
Always plot the boundary lines for better visualization alongside the fill.