How to Create Area Plot in Matplotlib: Simple Guide
To create an area plot in
matplotlib, use the plt.fill_between() function to fill the area between two curves or between a curve and the x-axis. This function takes x-values and y-values as inputs and fills the area under the curve, making it easy to visualize quantities over a range.Syntax
The basic syntax for creating an area plot is:
plt.fill_between(x, y1, y2=0, color=None, alpha=None)
Where:
x: Array of x-axis values.y1: Array of y-axis values for the upper boundary.y2: Array or scalar for the lower boundary (default is 0, the x-axis).color: Color to fill the area.alpha: Transparency level (0 transparent, 1 opaque).
python
plt.fill_between(x, y1, y2=0, color='blue', alpha=0.5)
Example
This example shows how to create a simple area plot filling the area under a sine wave curve.
python
import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 10, 500) y = np.sin(x) plt.fill_between(x, y, color='skyblue', alpha=0.5) plt.title('Area Plot of Sine Wave') plt.xlabel('x') plt.ylabel('sin(x)') plt.show()
Output
A plot window showing a smooth sine wave curve with the area under the curve filled in light blue color.
Common Pitfalls
Common mistakes when creating area plots include:
- Not matching the lengths of
xandyarrays, causing errors. - Forgetting to set
y2when filling between two curves, which defaults to zero and may not be desired. - Using opaque colors without transparency, which can hide gridlines or other plot elements.
python
import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 10, 100) y1 = np.sin(x) y2 = np.cos(x) # Wrong: y2 length mismatch # y2 = np.cos(x[:-1]) # This will cause an error # Correct usage: plt.fill_between(x, y1, y2, color='green', alpha=0.3) plt.title('Area Between Sine and Cosine') plt.show()
Output
A plot window showing the area filled between sine and cosine curves in translucent green.
Quick Reference
Tips for creating area plots with matplotlib:
- Use
plt.fill_between()to fill area under or between curves. - Set
alphato control transparency for better visualization. - Ensure
x,y1, andy2arrays have the same length. - Use colors that contrast well with the background and other plot elements.
Key Takeaways
Use plt.fill_between() to create area plots by filling between curves or between a curve and the x-axis.
Always ensure x and y arrays have matching lengths to avoid errors.
Adjust the alpha parameter to make the filled area transparent and keep the plot readable.
Specify y2 when filling between two curves to define the lower boundary explicitly.
Choose colors that make the filled area clear but not overwhelming.