如何更改用matplotlib绘制的图形大小?
转载于:https://stackoverflow.com/questions/332289/how-do-you-change-the-size-of-figures-drawn-with-matplotlib
Deprecation note:
As per the official Matplotlib guide, usage of thepylab
module is no longer recommended. Please consider using thematplotlib.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.
The first link in Google for 'matplotlib figure size'
is AdjustingImageSize (Google cache of the page).
Here's a test script from the above page. It creates test[1-3].png
files of different sizes of the same image:
#!/usr/bin/env python
"""
This is a small demo file that helps teach how to adjust figure sizes
for matplotlib
"""
import matplotlib
print "using MPL version:", matplotlib.__version__
matplotlib.use("WXAgg") # do this before pylab so you don'tget the default back end.
import pylab
import numpy as np
# Generate and plot some simple data:
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)
pylab.plot(x,y)
F = pylab.gcf()
# Now check everything with the defaults:
DPI = F.get_dpi()
print "DPI:", DPI
DefaultSize = F.get_size_inches()
print "Default size in Inches", DefaultSize
print "Which should result in a %i x %i Image"%(DPI*DefaultSize[0], DPI*DefaultSize[1])
# the default is 100dpi for savefig:
F.savefig("test1.png")
# this gives me a 797 x 566 pixel image, which is about 100 DPI
# Now make the image twice as big, while keeping the fonts and all the
# same size
F.set_size_inches( (DefaultSize[0]*2, DefaultSize[1]*2) )
Size = F.get_size_inches()
print "Size in Inches", Size
F.savefig("test2.png")
# this results in a 1595x1132 image
# Now make the image twice as big, making all the fonts and lines
# bigger too.
F.set_size_inches( DefaultSize )# resetthe size
Size = F.get_size_inches()
print "Size in Inches", Size
F.savefig("test3.png", dpi = (200)) # change the dpi
# this also results in a 1595x1132 image, but the fonts are larger.
Output:
using MPL version: 0.98.1
DPI: 80
Default size in Inches [ 8. 6.]
Which should result in a 640 x 480 Image
Size in Inches [ 16. 12.]
Size in Inches [ 16. 12.]
Two notes:
The module comments and the actual output differ.
This answer allows easily to combine all three images in one image file to see the difference in sizes.
figure tells you the call signature:
from matplotlib.pyplot import figure
figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')
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.
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)
Try commenting out the fig = ...
line
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2
fig = plt.figure(figsize=(18, 18))
plt.scatter(x, y, s=area, alpha=0.5)
plt.show()
This works well for me:
from matplotlib import pyplot as plt
F = gcf()
Size = F.get_size_inches()
F.set_size_inches(Size[0]*2, Size[1]*2, forward=True)#Set forward to True to resize window along with plot in figure.
plt.show() #or plt.imshow(z_array) if using an animation, where z_array is a matrix or numpy array
This might also help: http://matplotlib.1069221.n5.nabble.com/Resizing-figure-windows-td11424.html
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)
plt.show()
You need to set the figure size before you plot.
This resizes the figure immediately even after the figure has been drawn (at least using Qt4Agg/TkAgg - but not MacOSX - with matplotlib 1.4.0):
matplotlib.pyplot.get_current_fig_manager().resize(width_px, height_px)
To increase size of your figure N times you need to insert this just before your pl.show():
N = 2
params = pl.gcf()
plSize = params.get_size_inches()
params.set_size_inches( (plSize[0]*N, plSize[1]*N) )
It also works well with ipython notebook.
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))
In case you're looking for a way to change the figure size in Pandas, you could do e.g.:
df['some_column'].plot(figsize=(10, 5))
where df
is a Pandas dataframe. If you want to change the default settings, you could do the following:
import matplotlib
matplotlib.rc('figure', figsize=(10, 5))
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.
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (20,3)
This is very useful when you plot inline (e.g. with IPython Notebook).
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.
You can simply use (from matplotlib.figure.Figure):
fig.set_size_inches(width,height)
As of Matplotlib 2.0.0, changes to your canvas will be visible immediately, as the forward
keyword defaults to True
.
If you want to just change the width or height instead of both, you can use
fig.set_figwidth(val)
or fig.set_figheight(val)
These will also immediately update your canvas, but only in Matplotlib 2.2.0 and newer.
You need to specify forward=True
explicitly in order to live-update your canvas in versions older than what is specified above. Note that the set_figwidth
and set_figheight
functions don’t support the forward
parameter in versions older than Matplotlib 1.5.0.