How do you resize the figure dimensions when using Matplotlib subplots? | A1Lab@MZeeshanM to PythonEnglish • 5 days ago

How do you resize the figure dimensions when using Matplotlib subplots?

message-square
0

Pass figsize=(width, height) in inches directly to plt.subplots(nrows, ncols, figsize=(width, height)) when creating the figure—or resize an already-created figure afterward using fig.set_size_inches(width, height) (or fig.set_figwidth(...) / fig.set_figheight(...)).

Basic Example

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

# 1. Recommended: Pass figsize=(width, height) in inches to plt.subplots()
fig, axes = plt.subplots(1, 2, figsize=(12, 4), layout="constrained")

axes[0].plot(x, np.sin(x))
axes[0].set_title("Sine Wave")

axes[1].plot(x, np.cos(x), color="tab:orange")
axes[1].set_title("Cosine Wave")

# 2. Optional: Resize an existing Figure object dynamically after creation
fig.set_size_inches(14, 5)

plt.show()

Key Details & Edge Cases

  • Units are inches, not pixels (pixels = inches * dpi):
    • Matplotlib’s default figure size is (6.4, 4.8) inches at 100 DPI (640 × 480 pixels).
    • To target an exact pixel resolution (e.g., 1920 × 1080 px), divide pixel dimensions by dpi:
      dpi = 150
      fig, axes = plt.subplots(2, 2, figsize=(1920 / dpi, 1080 / dpi), dpi=dpi, layout="constrained")
      
  • Prevent overlapping subplot titles and axis labels (layout="constrained"):
    • Changing figsize (especially making multi-row or multi-column grids wider or shorter) often causes tick labels and subplot titles to collide. Pass layout="constrained" (or call fig.tight_layout()) so Matplotlib automatically recomputes subplot spacing to fit the new dimensions.
  • Avoid plt.figure(figsize=...) before plt.subplots(...):
    • Calling plt.figure(figsize=(10, 5)) followed by fig, axes = plt.subplots(2, 2) creates two separate figures—leaving the first 10 × 5 figure blank and creating the subplots at the default 6.4 × 4.8 size. Always pass figsize= directly into plt.subplots(..., figsize=(10, 5)).
  • Scaling figsize proportionally to grid rows and columns: For dynamic subplot grids where row/column counts vary, compute dimensions programmatically (e.g., figsize=(4 * ncols, 3 * nrows)) so every individual panel keeps a consistent aspect ratio.
  • Changing global default figure dimensions across all plots: Update rcParams at the start of a script or notebook:
    plt.rcParams["figure.figsize"] = (10, 6)
    
  • Preserving figsize when saving with plt.savefig(): Passing bbox_inches="tight" to fig.savefig("out.png", bbox_inches="tight") crops or expands the outer margins around labels, meaning the saved image’s pixel dimensions may differ slightly from figsize * dpi. Omit bbox_inches="tight" (and rely on layout="constrained") if exact output pixel dimensions are required.

Comparison of Figure Resizing Methods in Matplotlib

Method Syntax When Applied Modifies Existing Figure? Best Used When
plt.subplots(..., figsize=...) fig, ax = plt.subplots(2, 2, figsize=(10, 6)) At figure creation Creates new Figure Standard subplot workflows—cleanest single-call approach.
fig.set_size_inches(w, h) fig.set_size_inches(12, 5) After figure creation Yes (mutates fig) Resizing an existing figure returned by helper functions, Pandas .plot(), or Seaborn.
fig.set_figwidth() / set_figheight() fig.set_figwidth(12) After figure creation Yes (single axis only) Adjusting width or height independently while keeping the other dimension unchanged.
plt.rcParams["figure.figsize"] plt.rcParams["figure.figsize"] = (10, 5) Global session default Affects subsequent plots Setting a uniform default size across an entire Jupyter notebook or script.