How to Add Grid in Matplotlib: Simple Guide
To add a grid in Matplotlib, use the
plt.grid() function after creating your plot. You can customize the grid lines by passing parameters like color, linestyle, and linewidth inside plt.grid().Syntax
The basic syntax to add a grid in Matplotlib is:
plt.grid(True): Turns the grid on.plt.grid(False): Turns the grid off.plt.grid(axis='both'): Shows grid lines on both x and y axes.- You can customize grid lines using parameters like
color,linestyle, andlinewidth.
python
plt.grid(b=True, which='major', axis='both', color='gray', linestyle='--', linewidth=0.5)
Example
This example shows how to create a simple line plot and add a customized grid with dashed gray lines.
python
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [2, 3, 5, 7, 11] plt.plot(x, y, marker='o') plt.grid(True, color='gray', linestyle='--', linewidth=0.7) plt.title('Line Plot with Grid') plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.show()
Output
A line plot with points connected by a line and a gray dashed grid visible behind the plot lines.
Common Pitfalls
Common mistakes when adding grids include:
- Forgetting to call
plt.grid(True), so no grid appears. - Using
plt.grid()before plotting data, which still works but is less clear. - Not specifying the axis, leading to grid lines only on the default axis.
- Overusing thick or dark grid lines that clutter the plot.
Always call plt.grid() after plotting and customize grid style for clarity.
python
import matplotlib.pyplot as plt x = [1, 2, 3] y = [4, 5, 6] # Wrong: grid called before plot (still works but less clear) plt.grid(True) plt.plot(x, y) plt.show() # Right: grid called after plot plt.plot(x, y) plt.grid(True) plt.show()
Output
Two plots shown one after another, both with grid lines visible, but the second approach is clearer in code order.
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| b | Boolean to turn grid on/off | plt.grid(b=True) |
| which | Grid lines to show: 'major', 'minor', or 'both' | plt.grid(which='minor') |
| axis | Axis to apply grid: 'both', 'x', or 'y' | plt.grid(axis='x') |
| color | Color of grid lines | plt.grid(color='red') |
| linestyle | Style of grid lines | plt.grid(linestyle=':') |
| linewidth | Thickness of grid lines | plt.grid(linewidth=1.5) |
Key Takeaways
Use plt.grid(True) after plotting to show grid lines on your plot.
Customize grid appearance with parameters like color, linestyle, and linewidth.
Call plt.grid() after plotting for clearer and more readable code.
Specify axis='both', 'x', or 'y' to control where grid lines appear.
Avoid overly thick or dark grid lines to keep your plot clean.