October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

Matplotlib Subplot Grid Lines and Grid Spacing in Python

Use Axes.grid() to control tick-aligned grid lines inside Matplotlib panels, and adjust wspace and hspace separately to change the gaps between subplots.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In Matplotlib, grid lines inside a subplot and spacing between subplot panels are separate settings. Call grid() on each Axes to show and style its tick-aligned lines; use Figure.subplots_adjust() or GridSpec to change the gaps between panels.

Show grid lines on every subplot

plt.subplots() returns a Figure and one or more Axes. Each Axes represents a plotting panel, so apply grid() to each one you want to configure. For a two-by-two layout:

As an Amazon Associate I earn from qualifying purchases.

import matplotlib.pyplot as plt

fig, axs = plt.subplots(2, 2, figsize=(8, 6))

for ax in axs.flat:
    ax.plot([0, 1, 2], [0, 1, 4])
    ax.grid(visible=True, which="major", axis="both",
            color="gray", linestyle="--", linewidth=0.7, alpha=0.6)

fig.subplots_adjust(wspace=0.3, hspace=0.35)
plt.show()

The values for line style and spacing are illustrative; Matplotlib does not require these particular settings. The Axes.grid API documents the visibility, tick selection, axis selection, and line-style controls at Axes.grid.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose which grid lines appear

Use which to choose grid lines at major ticks, minor ticks, or both, and axis to choose x, y, or both axes:

  • ax.grid(True, which="major", axis="both") shows major grid lines in both directions.
  • ax.grid(True, which="minor", axis="x") shows minor grid lines along x.
  • ax.grid(True, which="both", axis="y") shows major and minor grid lines along y.

Grid lines align with tick positions. Enabling a minor grid does not set a custom numeric interval: configure minor ticks or an appropriate locator first. If the grid must fall at specific values, set the tick positions or locator deliberately, then enable the matching grid. Matplotlib’s guide explains the relationship between axes, ticks, and subplots: Axes and subplots.

Style the lines, and make visibility explicit

Grid styling accepts line properties such as color, linestyle, linewidth, and alpha. For example, ax.grid(visible=True, color="#888888", linestyle=":", linewidth=0.8, alpha=0.7) enables and styles the major grid by default.

In reusable code, specify visible=True or visible=False. Calling grid() without a visibility argument or style keywords toggles the current grid state, which can make repeated calls harder to reason about. If a grid seems to draw above or below other artists unexpectedly, line zorder alone may not determine its position: the API points to set_axisbelow or the Axis set_zorder method for draw order control.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Change the gaps between subplot panels

Use the Figure layout API when panels are too close together or too far apart:

fig.subplots_adjust(wspace=0.25, hspace=0.3)
  • wspace is the gap between columns, expressed as a fraction of the average Axes width.
  • hspace is the gap between rows, expressed as a fraction of the average Axes height.

These are relative layout units, not pixels or points. Unspecified values retain their current settings; the initial values come from the figure.subplot.* rcParams. See the Figure API for subplots_adjust and related layout controls.

Use GridSpec for uneven panel sizes

For more involved layouts, pass settings through gridspec_kw when creating subplots, or set width and height ratios directly:

fig, axs = plt.subplots(
    2, 2,
    gridspec_kw={"width_ratios": [2, 1], "wspace": 0.25, "hspace": 0.3}
)

The width ratio makes the left column twice the relative width of the right column; it does not specify an absolute size. height_ratios works similarly for rows. The official example shows relative sizing and spacing controls such as left, right, top, and bottom: GridSpec with variable sizes and spacing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set defaults for grid style or subplot spacing

For consistent settings across figures, Matplotlib separates grid appearance from panel layout in its configuration parameters. Grid appearance uses settings such as axes.grid, axes.grid.axis, axes.grid.which, and grid.color, grid.linestyle, grid.linewidth, and grid.alpha; major and minor grids can also have overrides. Figure-level panel gaps use figure.subplot.wspace and figure.subplot.hspace. These parameters are documented in Matplotlib configuration: rcParams.

Automatic constrained layout has its own spacing and padding controls. Choose a layout strategy deliberately, then inspect the rendered figure: titles, axis labels, and tick labels can affect the space a layout needs.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Which setting should you change?

What looks wrong Change
Grid lines within a panel are too dense, sparse, or in the wrong places Set that Axes’ major or minor tick positions or locator, then enable the corresponding grid.
Neighboring panels feel crowded or too separated Adjust Figure or GridSpec wspace and hspace.
Panels need different relative widths or heights Use width_ratios or height_ratios in the subplot GridSpec settings.
Many figures should share the same grid appearance Set grid-related rcParams, or configure each Axes locally with ax.grid().

Handle a single subplot safely

With multiple rows or columns, axs.flat is a convenient way to loop through the Axes array. With only one subplot, plt.subplots() may return a single Axes object instead of an array, so axs.flat will not work. If you want array-shaped results regardless of subplot count, request squeeze=False:

fig, axs = plt.subplots(1, 1, squeeze=False)
for ax in axs.flat:
    ax.grid(visible=True)

The behavior depends on the number of requested subplots; the Figure API documents the subplot-creation options.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.