Skip to content

Matplotlib - 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.

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.

The ax.grid() method accepts several keyword arguments to customize the grid’s appearance:

  • visible (or positional bool): True to show the grid, False to 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 (or ls): Sets the line style (e.g., '-', '--', ':', '-.').
  • linewidth (or lw): 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 plt
import numpy as np
import matplotlib.ticker as mticker
# Prepare data
x = np.linspace(0, 10, 50)
y1 = x**2
y2 = 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 grid
axes[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 grid
axes[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 ticks
axes[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 context
for ax in axes:
ax.set_xlabel('X Value')
ax.set_ylabel('Y Value')
fig.tight_layout()
plt.show()

This example shows:

  1. A plot with the default grid enabled.
  2. A plot with a customized major grid (blue, dash-dot lines).
  3. 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 MinorLocator or ax.minorticks_on()) for the minor grid to be visible.