How to Change the Figure Size in Matplotlib

Jinku Hu Feb 02, 2024
  1. Set Figure Size When Initiating the Figure in Matplotlib
  2. rcParams to Set the Figure Size in Matplotlib
  3. set_size_inches to Change the Figure Size in Matplotlib After a Figure Is Created
How to Change the Figure Size in Matplotlib

We could set and also change the figure size drawn in Matplotlib. This tutorial will demonstrate how to manipulate the figure size before and after the figure is created.

Set Figure Size When Initiating the Figure in Matplotlib

pyplot.figure creates a new figure with the attributes given in the parameters, where figsize defines the figure size in inches.

figsize to Set the Figure Size in Matplotlib

from matplotlib import pyplot as plt

plt.figure(figsize=(4, 4))
plt.show()

rcParams to Set the Figure Size in Matplotlib

rcParams is the dictionary object including the properties in Matplotlib. We could assign the figure size as the value to the key figure.figsize in rcParams.

from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = (4, 4)
plt.plot([[1, 2], [3, 4]])
plt.show()

plt.rcParams could be placed before or after plt.plot. Any figure created in the same scripts will share the same figure size as assigned.

You could assign the figure.figsize multiple times in the same scripts, but only the first setting is applied to the created figures.

from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = (6, 6)
plt.plot([[1, 2], [3, 4]])
plt.figure()
plt.rcParams["figure.figsize"] = (2, 2)
plt.plot([[1, 2], [3, 4]])
plt.show()

Both figures have the size as (6, 6) but not (2, 2).

set_size_inches to Change the Figure Size in Matplotlib After a Figure Is Created

If the figure has already been created, we could use set_size_inches to change the figure size in Matplotlib.

from matplotlib import pyplot as plt

fig1 = plt.figure(1)
plt.plot([[1, 2], [3, 4]])
fig2 = plt.figure(2)
plt.plot([[1, 2], [3, 4]])

fig1.set_size_inches(3, 3)
fig2.set_size_inches(4, 4)

plt.show()

Here, fig1 and fig2 are references to the two created figures.

set_size_inches has the option forward with the default value as True that means the canvas size will be automatically updated after the new size is given.

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

Related Article - Matplotlib Figure