0
0
MatplotlibHow-ToBeginner ยท 4 min read

How to Use GridSpec in Matplotlib for Flexible Layouts

Use matplotlib.gridspec.GridSpec to create a grid layout for subplots by specifying rows and columns. Then assign subplots to grid positions using fig.add_subplot(gs[row, col]) for flexible and precise subplot arrangements.
๐Ÿ“

Syntax

The basic syntax to use GridSpec is:

  • gs = GridSpec(nrows, ncols): creates a grid with nrows rows and ncols columns.
  • fig.add_subplot(gs[row, col]): adds a subplot at the specified grid position.
  • You can also select multiple cells like gs[row_start:row_end, col_start:col_end] to span subplots across multiple grid cells.
python
from matplotlib.gridspec import GridSpec
import matplotlib.pyplot as plt

fig = plt.figure()
gs = GridSpec(2, 3, figure=fig)  # 2 rows, 3 columns

ax1 = fig.add_subplot(gs[0, 0])  # first row, first column
ax2 = fig.add_subplot(gs[0, 1:3])  # first row, columns 2 and 3
ax3 = fig.add_subplot(gs[1, :])  # second row, all columns

plt.show()
Output
A figure window with three subplots arranged in a 2x3 grid: one in the top-left cell, one spanning the top row's last two cells, and one spanning the entire bottom row.
๐Ÿ’ป

Example

This example shows how to create a figure with four subplots arranged in a 2x2 grid using GridSpec. It demonstrates how to control subplot positions and sizes precisely.

python
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure(figsize=(6, 4))
gs = GridSpec(2, 2, figure=fig)

ax1 = fig.add_subplot(gs[0, 0])
ax1.plot([1, 2, 3], [1, 4, 9])
ax1.set_title('Plot 1')

ax2 = fig.add_subplot(gs[0, 1])
ax2.plot([1, 2, 3], [9, 4, 1])
ax2.set_title('Plot 2')

ax3 = fig.add_subplot(gs[1, 0])
ax3.plot([1, 2, 3], [2, 3, 2])
ax3.set_title('Plot 3')

ax4 = fig.add_subplot(gs[1, 1])
ax4.plot([1, 2, 3], [3, 2, 3])
ax4.set_title('Plot 4')

plt.tight_layout()
plt.show()
Output
A figure with four subplots arranged in a 2x2 grid, each showing a simple line plot with titles 'Plot 1' to 'Plot 4'.
โš ๏ธ

Common Pitfalls

Common mistakes when using GridSpec include:

  • Not creating a figure before using GridSpec, which causes errors.
  • Using incorrect slicing syntax for grid positions, like mixing up row and column indices.
  • Forgetting to call plt.tight_layout() to avoid overlapping subplots.
  • Trying to add multiple subplots to the same grid cell without spanning.
python
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure()
gs = GridSpec(2, 2, figure=fig)

# Wrong: overlapping subplots in the same cell
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 0])  # This will overlap ax1

# Right: use different cells or span
ax3 = fig.add_subplot(gs[0, 0])
ax4 = fig.add_subplot(gs[0, 1])

plt.show()
Output
A figure window showing two subplots overlapping in the top-left cell (wrong), then corrected by placing subplots in separate cells.
๐Ÿ“Š

Quick Reference

GridSpec quick tips:

  • Create grid: gs = GridSpec(rows, cols)
  • Add subplot: fig.add_subplot(gs[row, col])
  • Span cells: gs[row_start:row_end, col_start:col_end]
  • Use plt.tight_layout() to avoid overlap.
  • GridSpec can be nested for complex layouts.
โœ…

Key Takeaways

GridSpec lets you create flexible subplot layouts by dividing the figure into rows and columns.
Use slicing with GridSpec to make subplots span multiple grid cells.
Always create a figure before using GridSpec and add subplots referencing the grid.
Call plt.tight_layout() to prevent subplot labels and titles from overlapping.
Avoid placing multiple subplots in the same grid cell unless intentionally overlapping.