How to change the figure size in Matplotlib

  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

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.

comments powered by Disqus