I don’t use Matplotlib much, but I always wondered how I could set the figure size to the exact size I want, especially the saved ones. Not just still images, but also animations.

While remaking an animation about sound spectrum, I found How to change size of Matplotlib plot, not entirely enough but close for me to find the complete solution.

And here is all I have done to make that happen:


import matplotlib.pyplot as plt

WIDTH = 1280
HEIGHT = 720

dpi = plt.rcParams['figure.dpi']
plt.rcParams['savefig.dpi'] = dpi
plt.rcParams["figure.figsize"] = (1.0 * WIDTH / dpi, 1.0 * HEIGHT / dpi)

fig = plt.figure()

Only five lines are added to dynamatically change rc settings. I use figure.dpi for saving and calculation the size in terms of inches. By default,

  • figure.dpi is 80 DPI,
  • savefig.dpi is 100 DPI, and
  • figure.figsize is (8, 6).

The key isn’t just changing figure.figsize, because it’s not enough since the displaying and saving DPIs are different, you must also change the saving DPI.