Course contentsShow
← Python
Lesson 984 of 1,06015. Data Science FundamentalsFree lesson

Customizing Figure Layouts and Subplot Arrangements

Control the spatial organization of multiple plots within a single figure to create cohesive and readable data dashboards.

In this lesson, you will learn how to orchestrate complex dashboard visualizations by precisely controlling the spatial geometry of multiple subplots within a single figure.

When building dashboards, you often need more than a standard grid. Sometimes you need a tall main plot next to two smaller ones, or a figure that spans the entire width of the dashboard. While basic subplots offer rigid rows and columns, advanced layout control allows you to treat your figure as a canvas where you define the specific "footprint" of each visual element.

In matplotlib, we use the GridSpec object to define a grid layout, then assign subplots to specific slices of that grid. This approach breaks the figure into a coordinate system, allowing plots to span across multiple rows or columns.

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# Create a figure with a 2x2 grid layout
fig = plt.figure(figsize=(10, 6))
gs = gridspec.GridSpec(2, 2, height_ratios=[1, 2])

# Plot A takes the top row (spans 2 columns)
ax1 = fig.add_subplot(gs[0, :])
ax1.set_title("Top Dashboard Overview")

# Plot B takes the bottom left
ax2 = fig.add_subplot(gs[1, 0])
ax2.set_title("Detailed Metric 1")

# Plot C takes the bottom right
ax3 = fig.add_subplot(gs[1, 1])
ax3.set_title("Detailed Metric 2")

plt.tight_layout()
plt.show()

By passing slice objects to the GridSpec, you can define custom arrangements:

  • gs[0, :]: Spans the entire first row.
  • gs[1, 0]: Occupies only the bottom-left quadrant.
  • height_ratios: Adjusts the relative vertical size of rows, ensuring your primary visualizations have more breathing room than secondary annotations.

Beyond GridSpec, always conclude your layout configuration with plt.tight_layout(). This crucial final step automatically adjusts subplot parameters so that axes labels and titles don't overlap, ensuring the dashboard remains professional and readable. Mastering these spatial arrangements transforms a collection of individual charts into a singular, cohesive narrative.

Key Takeaway: By utilizing GridSpec and spanning subplots across specific grid coordinates, you gain granular control over the hierarchy and visual weight of your data dashboard components.