5 Best Ways to Plot Grids Across Subplots in Python Matplotlib

πŸ’‘ Problem Formulation: Python’s Matplotlib library is a powerful tool for creating visualizations, but users often face challenges when trying to customize the appearance of subplot grids. This article addresses the specific problem of plotting and customizing grid lines across multiple subplots within a figure in Matplotlib. We aim to demonstrate how to add grid lines that enhance the readability and aesthetic appeal of complex multi-graph layouts. The desired output is a series of neatly organized subplots with clearly visible grid lines.

Method 1: Using subplot with ax.grid()

In Matplotlib, the ax.grid() function can be called on each subplot (axis) object to toggle the visibility of grid lines. This method offers an easy-to-use approach for adding grids to individual subplots and provides customization options such as line style and color.

Here’s an example:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 2)
for a in ax.flatten():
    a.plot(range(10), range(10))
    a.grid(True)

plt.show()

The output is a 2×2 array of subplots, each containing a straight line graph with grid lines overlaying the plotting area.

This code snippet quickly demonstrates the use of a loop to apply grid lines to all subplots created by plt.subplots(). The ax.flatten() method turns a two-dimensional array of subplots into a flat one-dimensional iterator for easy looping, with each subplot receiving a call to a.grid(True) to turn on grid lines.

Method 2: Customizing Grid Appearance with grid() Parameters

Customizing grid appearance in subplots is straightforward using the grid() function’s parameters such as color, linestyle, and linewidth. Each subplot can have uniquely styled grid lines, providing precise control over the visual output.

Here’s an example:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(1, 3)
styles = ['-', '--', ':']
colors = ['r', 'g', 'b']
widths = [1, 2, 3]

for a, style, color, width in zip(ax, styles, colors, widths):
    a.plot(range(10), range(10))
    a.grid(True, linestyle=style, color=color, linewidth=width)

plt.show()

The output is a 1×3 array of subplots, where each subplot features a different grid line style, color, and line width.

This code snippet uses zip to pair each subplot with a set of grid customization parameters from the styles, colors, and widths lists. Each subplot is then modified to have its grid appearance according to the provided attributes.

Method 3: Toggling Grid Lines for Specific Axes with which Parameter

Matplotlib’s grid() function includes a which parameter, allowing users to specify whether to apply grid lines to major, minor, or both tick marks. This targeted application of grid lines is beneficial for viewers when differentiating between main and secondary data points.

Here’s an example:

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

fig, ax = plt.subplots()
ax.plot(range(100), range(100))

ax.xaxis.set_major_locator(ticker.MultipleLocator(20))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(5))
ax.yaxis.set_major_locator(ticker.MultipleLocator(20))
ax.yaxis.set_minor_locator(ticker.MultipleLocator(5))

ax.grid(which='major', color='b', linestyle='-', linewidth=2)
ax.grid(which='minor', color='r', linestyle=':', linewidth=1)

plt.show()

The output is a single subplot with blue solid major grid lines and red dotted minor grid lines.

The which parameter selectively applies different styles to major and minor grid lines, enhancing readability. Tick locators are first set to specify the positions of major and minor ticks before calling ax.grid() with appropriate styles for major and minor grid lines.

Method 4: Combining Grids with Multiple Axes and Shared Axes

Creating complex plots with shared axes in Matplotlib can benefit from shared grid lines, which make the figure more coherent. By sharing axes, grid lines naturally align across the linked subplots, which is crucial for comparing multiple data sets.

Here’s an example:

import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(range(10), range(10))
ax2.plot(range(10), reversed(range(10)))
ax1.grid(True)
ax2.grid(True)

plt.show()

The output is two horizontally aligned subplots with matching y-axes and grids.

This code snippet creates two subplots with the sharey=True argument, meaning they share the same y-axis. Grids are applied on both axes, ensuring they align perfectly across subplots, resulting in a more unified visualization.

Bonus One-Liner Method 5: Enabling Grids with pyplot

The pyplot interface provides a quick one-liner to turn on grids for all subplots within the current figure. This method is suitable for cases where uniform grids on all subplots are desirable.

Here’s an example:

import matplotlib.pyplot as plt

fig, _ = plt.subplots(2, 2)
plt.grid(True)
plt.show()

The output is a 2×2 array of subplots with grid lines enabled on each subplot.

By calling plt.grid(True), grid lines are toggled on for each of the current figure’s subplots. While this method offers less customization, it provides a simple and fast way to enable grids uniformly across the figure.

Summary/Discussion

  • Method 1: Individual grid toggling with ax.grid(). Strengths: Simple, easy to understand. Weaknesses: Requires iterating through subplots if many are present.
  • Method 2: Custom grid styles. Strengths: Highly customizable, allows diverse grid appearances. Weaknesses: More code needed for styling.
  • Method 3: Grid lines for specific ticks with which parameter. Strengths: Enhanced readability, distinction between major/minor data points. Weaknesses: Additional setup for tick locators.
  • Method 4: Shared axes grid lines. Strengths: Aligns grids across subplots, good for comparison plots. Weaknesses: Only applies to shared axes scenarios.
  • Method 5: Pyplot one-liner for grids. Strengths: Quick and easy. Weaknesses: Limited customization, applies uniformly to all subplots.