How do you change the size of figure drawn with matplotlib?
I always use the following pattern:
x_inches = 150*(1/25.4) # [mm]*constant
y_inches = x_inches*(0.8)
dpi = 96
fig = plt.figure(1, figsize = (x_inches,y_inches), dpi = dpi, constrained_layout = True)
With this example you are able to set figure dimensions in inches or in milimiters and setting constrained_layout
to True
plots fill your figure without borders.
You directly change the figure size by using
plt.set_figsize(figure=(10, 10))
Since Matplotlib isn't able to use the metric system natively, if you want to specify the size of your figure in a reasonable unit of length such as centimeters, you can do the following (code from gns-ank):
def cm2inch(*tupl):
inch = 2.54
if isinstance(tupl[0], tuple):
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl)
Then you can use:
plt.figure(figsize=cm2inch(21, 29.7))
If you've already got the figure created you can quickly do this:
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)
import matplotlib.pyplot as plt
plt.figure(figsize=(20,10))
plt.plot(x,y) ## This is your plot
plt.show()
You can also use:
fig, ax = plt.subplots(figsize=(20, 10))
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 @asamaier noticed is preferable to not put this statement in the same cell of the imports statements.
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 to this question.