Course contentsShow
← Data Science
Lesson 1278 of 2,14532. Visualization with Matplotlib and SeabornFree lesson

GridSpec for Complex Layouts

Create asymmetric and custom subplot arrangements using GridSpec for advanced multi-panel visualizations.

GridSpec for Complex Layouts

You'll learn how to create asymmetric, multi-panel visualizations where subplots span different numbers of rows and columns.

The Core Idea

So far, plt.subplots() has given you neat, uniform grids—every subplot is the same size. But real-world dashboards and reports often need asymmetric layouts: a large main plot with several smaller supporting panels, or a side-by-side comparison where one chart is twice as wide as another.

GridSpec lets you treat your figure like a flexible grid where subplots can span multiple cells, much like merging cells in a spreadsheet. You define the grid dimensions, then assign subplots to specific slices of that grid.

How It Works

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

fig = plt.figure(figsize=(10, 6))
gs = GridSpec(3, 3, figure=fig)  # 3 rows, 3 columns

# Large plot spanning 2 rows and all 3 columns
ax1 = fig.add_subplot(gs[0:2, :])
ax1.plot([1, 2, 3], [4, 5, 6])
ax1.set_title("Main Plot (2 rows × 3 cols)")

# Two smaller plots in the bottom row
ax2 = fig.add_subplot(gs[2, 0:2])  # Bottom-left, spans 2 cols
ax2.bar([1, 2], [3, 4])
ax2.set_title("Left Detail")

ax3 = fig.add_subplot(gs[2, 2])  # Bottom-right, 1 cell
ax3.scatter([1, 2], [2, 1])
ax3.set_title("Right Detail")

plt.tight_layout()
plt.show()

The slicing syntax gs[row_slice, col_slice] lets you assign any rectangular region to a subplot, giving you complete control over the layout architecture.

Key Takeaway:
GridSpec transforms your figure into a flexible grid where subplots can span arbitrary rows and columns, enabling professional, asymmetric multi-panel layouts that go far beyond uniform grids.