How do I change the size of figures drawn with Matplotlib?

Learn how do i change the size of figures drawn with matplotlib? with practical examples, diagrams, and best practices. Covers python, pandas, matplotlib development techniques with visual explanat...

Mastering Matplotlib Figure Sizes: A Comprehensive Guide

Hero image for How do I change the size of figures drawn with Matplotlib?

Learn how to effectively control the size of your Matplotlib figures and subplots for better visualization and presentation in Python.

Matplotlib is a powerful plotting library in Python, widely used for creating static, animated, and interactive visualizations. One of the most common requirements when working with Matplotlib is to control the size of the figures you generate. Whether you're preparing plots for a presentation, a paper, or a dashboard, getting the dimensions right is crucial for readability and aesthetic appeal. This article will guide you through various methods to adjust figure sizes, from initial creation to modifying existing plots, ensuring your visualizations always look their best.

Understanding Figure Size in Matplotlib

In Matplotlib, the 'figure' is the top-level container for all plot elements. It's like the canvas on which you draw your plots. The size of this canvas is defined by its width and height, typically measured in inches. When you create a figure, you can specify these dimensions using the figsize argument. This argument takes a tuple (width, height).

flowchart TD
    A[Start Plotting] --> B{Need to set Figure Size?}
    B -- Yes --> C[Use `plt.figure(figsize=(width, height))`]
    B -- No --> D[Default Figure Size]
    C --> E[Add Subplots/Axes]
    D --> E
    E --> F[Plot Data]
    F --> G[Save/Display Figure]
    G --> H[End]

Workflow for setting Matplotlib figure size.

Method 1: Setting Figure Size During Creation

The most straightforward way to set the figure size is when you initially create the figure using plt.figure() or plt.subplots(). The figsize parameter expects a tuple of two numbers, representing the width and height in inches. Remember that Matplotlib's default DPI (dots per inch) is usually 100, so a figsize=(6, 4) would result in an image 600x400 pixels if saved without specifying DPI.

import matplotlib.pyplot as plt

# Method 1a: Using plt.figure()
fig = plt.figure(figsize=(10, 6)) # 10 inches wide, 6 inches tall
ax = fig.add_subplot(111)
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title('Figure created with plt.figure()')
plt.show()

# Method 1b: Using plt.subplots() (recommended for most cases)
fig, ax = plt.subplots(figsize=(8, 5)) # 8 inches wide, 5 inches tall
ax.plot([1, 2, 3], [6, 5, 4])
ax.set_title('Figure created with plt.subplots()')
plt.show()

Setting figure size using plt.figure() and plt.subplots().

Method 2: Changing Figure Size After Creation

Sometimes you might need to adjust the figure size after it has already been created, perhaps dynamically based on data or user input. You can achieve this using the set_size_inches() method of the Figure object. This method also takes a tuple (width, height) in inches.

import matplotlib.pyplot as plt

# Create a figure with default size
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 2, 1])
ax.set_title('Default Size Figure')
plt.show()

# Change the size of the existing figure
fig.set_size_inches(12, 4) # Make it wider and shorter
ax.set_title('Resized Figure')
plt.show()

# You can also set width and height individually
fig.set_figwidth(7)
fig.set_figheight(7)
ax.set_title('Individually Sized Figure')
plt.show()

Adjusting figure size after creation using set_size_inches().

Method 3: Global Configuration with rcParams

For consistent figure sizing across multiple plots in a script or project, you can modify Matplotlib's default runtime configuration parameters (rcParams). This allows you to set a global default figsize that will apply to all subsequent figures created without an explicit figsize argument.

import matplotlib.pyplot as plt

# Set global default figure size
plt.rcParams['figure.figsize'] = (11, 7) # All new figures will be 11x7 inches

# Create a figure without specifying figsize
fig1, ax1 = plt.subplots()
ax1.plot([1, 2, 3], [10, 12, 11])
ax1.set_title('Figure with rcParams default size')
plt.show()

# You can still override the default for specific figures
fig2, ax2 = plt.subplots(figsize=(5, 5))
ax2.plot([1, 2, 3], [1, 0, 1])
ax2.set_title('Figure with overridden size')
plt.show()

# Reset rcParams to default if needed
plt.rcParams.update(plt.rcParamsDefault)

Using rcParams to set a global default figure size.

Considering DPI (Dots Per Inch)

While figsize determines the physical dimensions (in inches), the dpi (dots per inch) parameter determines the resolution of the output image. A higher DPI means more pixels per inch, resulting in a sharper image, especially when saving to raster formats like PNG or JPEG. The total pixel dimensions are width_inches * dpi by height_inches * dpi.

import matplotlib.pyplot as plt

# Create a figure with specific figsize and dpi
fig, ax = plt.subplots(figsize=(6, 4), dpi=150) # 6 inches x 150 dpi = 900 pixels wide
ax.plot([0, 1], [0, 1])
ax.set_title('High DPI Figure')
plt.savefig('high_dpi_figure.png', dpi=150) # Ensure saved image also uses high DPI
plt.show()

Specifying DPI during figure creation and saving.