Skip to content

Matplotlib - Subplot2grid() Function

Matplotlib - Using subplot2grid() for Complex Layouts

Section titled “Matplotlib - Using subplot2grid() for Complex Layouts”

While plt.subplots() is excellent for creating regular grids, sometimes you need more complex layouts where subplots might span multiple rows or columns. The plt.subplot2grid() function offers this flexibility.

It allows you to place an Axes object onto a conceptual grid, specifying its starting location and how many rows/columns it should occupy.

ax = plt.subplot2grid(shape, loc, rowspan=1, colspan=1)

Arguments:

  • shape: A tuple (nrows, ncols) defining the geometry of the overall grid.
  • loc: A tuple (row, col) specifying the starting cell (0-indexed) for the subplot within the grid.
  • rowspan: Integer (default 1) indicating how many rows the subplot should span downwards from loc.
  • colspan: Integer (default 1) indicating how many columns the subplot should span to the right from loc.

Note: While subplot2grid provides flexibility, for highly complex or nested grid layouts, the matplotlib.gridspec module often offers a more powerful and arguably more readable approach. However, subplot2grid is useful for moderately complex arrangements.

Example: Creating a layout with differently sized subplots.

import matplotlib.pyplot as plt
import numpy as np
# Prepare some data
x = np.arange(1, 10)
plt.figure(figsize=(9, 6)) # Create the figure first
# --- Define the subplot layout using subplot2grid ---
# Plot 1: Spans 2 columns in the first row of a 3x3 grid
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=2)
ax1.plot(x, np.exp(x/3), color='blue')
ax1.set_title('Plot 1 (exp, colspan=2)')
# Plot 2: Spans 3 rows in the last column of a 3x3 grid
ax2 = plt.subplot2grid((3, 3), (0, 2), rowspan=3)
ax2.plot(x, x*x, color='red')
ax2.set_title('Plot 2 (square, rowspan=3)')
# Plot 3: Spans 2 rows and 2 columns starting from row 1, col 0
ax3 = plt.subplot2grid((3, 3), (1, 0), rowspan=2, colspan=2)
ax3.plot(x, np.log(x), color='green')
ax3.set_title('Plot 3 (log, rowspan=2, colspan=2)')
# --- Final adjustments ---
plt.suptitle('Complex Layout with subplot2grid()', fontsize=16)
# Adjust layout to prevent overlapping titles/labels
plt.tight_layout(rect=[0, 0, 1, 0.95]) # Adjust rect for suptitle
plt.show()

In this example, we define a conceptual 3x3 grid.

  • ax1 starts at (0, 0) and spans 2 columns (colspan=2).
  • ax2 starts at (0, 2) and spans 3 rows (rowspan=3).
  • ax3 starts at (1, 0) and spans 2 rows (rowspan=2) and 2 columns (colspan=2).

subplot2grid allows creating non-uniform layouts that would be difficult or impossible with a simple plt.subplots() call. Remember that coordinates (loc) are 0-indexed.