python - How do you change the size of figures drawn with Matplotlib?

ID : 240

viewed : 140

Tags : pythongraphmatplotlibvisualizationpython

Top 5 Answer for python - How do you change the size of figures drawn with Matplotlib?

vote vote


figure tells you the call signature:

from matplotlib.pyplot import figure  figure(figsize=(8, 6), dpi=80) 

figure(figsize=(1,1)) would create an inch-by-inch image, which would be 80-by-80 pixels unless you also give a different dpi argument.

vote vote


If you've already got the figure created, you can use figure.set_size_inches to adjust the figure size:

fig = matplotlib.pyplot.gcf() fig.set_size_inches(18.5, 10.5) fig.savefig('test2png.png', dpi=100) 

To propagate the size change to an existing GUI window, add forward=True:

fig.set_size_inches(18.5, 10.5, forward=True) 

Additionally as Erik Shilts mentioned in the comments you can also use figure.set_dpi to "[s]et the resolution of the figure in dots-per-inch"

vote vote


Using plt.rcParams

There is also this workaround in case you want to change the size without using the figure environment. So in case you are using plt.plot() for example, you can set a tuple with width and height.

import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = (20,3) 

This is very useful when you plot inline (e.g., with IPython Notebook). As asmaier noticed, it is preferable to not put this statement in the same cell of the imports statements.

To reset the global figure size back to default for subsequent plots:

plt.rcParams["figure.figsize"] = plt.rcParamsDefault["figure.figsize"] 

Conversion to cm

The figsize tuple accepts inches, so if you want to set it in centimetres you have to divide them by 2.54. Have a look at this question.

vote vote


Deprecation note:
As per the official Matplotlib guide, usage of the pylab module is no longer recommended. Please consider using the matplotlib.pyplot module instead, as described by this other answer.

The following seems to work:

from pylab import rcParams rcParams['figure.figsize'] = 5, 10 

This makes the figure's width 5 inches, and its height 10 inches.

The Figure class then uses this as the default value for one of its arguments.

vote vote


Please try a simple code as following:

from matplotlib import pyplot as plt plt.figure(figsize=(1,1)) x = [1,2,3] plt.plot(x, x) 

You need to set the figure size before you plot.

Top 3 video Explaining python - How do you change the size of figures drawn with Matplotlib?