Matplotlib - Grids
Matplotlib - Adding Grids
Section titled “Matplotlib - Adding Grids”Grid lines can significantly improve the readability of plots by making it easier to estimate the values of data points and compare them against the axes scales. Matplotlib provides a simple way to add and customize grid lines using the ax.grid() method.
Basic Usage
Section titled “Basic Usage”Calling ax.grid(True) turns on the major grid lines for both the x and y axes using default settings (typically light gray, solid lines).
Calling ax.grid(False) turns the grid off.
Customization Options
Section titled “Customization Options”The ax.grid() method accepts several keyword arguments to customize the grid’s appearance:
visible(or positional bool):Trueto show the grid,Falseto hide it.which: Specifies which grid lines to affect. Options are'major'(default),'minor', or'both'.axis: Specifies which axis’s grid lines to affect. Options are'x','y', or'both'(default).color: Sets the color of the grid lines (e.g.,'gray','red','#cccccc').linestyle(orls): Sets the line style (e.g.,'-','--',':','-.').linewidth(orlw): Sets the thickness of the grid lines.alpha: Sets the transparency of the grid lines (0.0 to 1.0).
You can call ax.grid() multiple times with different settings to apply different styles to major/minor grids or x/y grids.
Example demonstrating different grid configurations:
import matplotlib.pyplot as pltimport numpy as npimport matplotlib.ticker as mticker
# Prepare datax = np.linspace(0, 10, 50)y1 = x**2y2 = np.exp(x / 3)y3 = np.sin(x) * 10
fig, axes = plt.subplots(1, 3, figsize=(15, 5), sharey=False)
# --- Plot 1: Default Grid ---axes[0].plot(x, y1, 'g', lw=2)axes[0].grid(True) # Simple default gridaxes[0].set_title('Default Grid (grid(True))')
# --- Plot 2: Custom Major Grid ---axes[1].plot(x, y2, 'r')axes[1].grid(visible=True, which='major', axis='both', color='blue', linestyle='-.', linewidth=0.75, alpha=0.5)axes[1].set_title('Custom Major Grid')
# --- Plot 3: Custom Major and Minor Grids ---axes[2].plot(x, y3, 'purple')
# Customize major gridaxes[2].grid(visible=True, which='major', axis='y', linestyle='-', color='black', alpha=0.6)# Customize minor grid (need minor ticks enabled first)axes[2].yaxis.set_minor_locator(mticker.AutoMinorLocator(5)) # Add minor ticksaxes[2].grid(visible=True, which='minor', axis='y', linestyle=':', color='gray', alpha=0.4)
axes[2].set_title('Major (Y only) & Minor Grid (Y only)')
# Add labels to all for contextfor ax in axes: ax.set_xlabel('X Value') ax.set_ylabel('Y Value')
fig.tight_layout()plt.show()This example shows:
- A plot with the default grid enabled.
- A plot with a customized major grid (blue, dash-dot lines).
- A plot with different styles for the major (solid black) and minor (dotted gray) grid lines on the y-axis only. Note that minor ticks need to be enabled (e.g., using a
MinorLocatororax.minorticks_on()) for the minor grid to be visible.