0
0
Matplotlibdata~7 mins

GridSpec for complex layouts in Matplotlib

Choose your learning style9 modes available
Introduction

GridSpec helps you arrange multiple plots in a grid with different sizes and positions. It makes complex layouts easy to create.

You want to show several charts in one figure with different sizes.
You need to place one big plot next to smaller plots.
You want to control spacing between plots precisely.
You want to combine bar charts and line charts in one figure.
You want to create a dashboard-like layout with multiple plots.
Syntax
Matplotlib
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure()
gs = GridSpec(nrows, ncols, figure=fig)

ax1 = fig.add_subplot(gs[row_start:row_end, col_start:col_end])

GridSpec divides the figure into a grid of rows and columns.

You select where each plot goes by slicing the grid with row and column ranges.

Examples
This creates a 2x2 grid. The bottom plot spans both columns.
Matplotlib
gs = GridSpec(2, 2, figure=fig)
ax1 = fig.add_subplot(gs[0, 0])  # Top-left plot
ax2 = fig.add_subplot(gs[0, 1])  # Top-right plot
ax3 = fig.add_subplot(gs[1, :])  # Bottom plot spanning two columns
Here, plots cover different parts of the grid for a custom layout.
Matplotlib
gs = GridSpec(3, 3, figure=fig)
ax1 = fig.add_subplot(gs[0, :2])  # Top row, first two columns
ax2 = fig.add_subplot(gs[1:, 2])  # Last two rows, last column
Sample Program

This code creates a figure with 4 plots arranged in a 2x3 grid. Each plot uses different grid cells to create a complex layout.

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

fig = plt.figure(figsize=(6, 4))
gs = GridSpec(2, 3, 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.bar(['A', 'B', 'C'], [3, 7, 5])
ax2.set_title('Plot 2')

ax3 = fig.add_subplot(gs[1, :2])
ax3.scatter([1, 2, 3], [9, 5, 1])
ax3.set_title('Plot 3')

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

plt.tight_layout()
plt.show()
OutputSuccess
Important Notes

Use plt.tight_layout() to avoid overlapping labels and titles.

You can combine GridSpec with subplot_kw to customize each subplot.

Remember that row and column indices start at 0.

Summary

GridSpec divides a figure into a grid for flexible plot placement.

You select plot positions by slicing the grid rows and columns.

It helps create complex, clean layouts with multiple plots.