您如何更改用matplotlib绘制的图形的大小?

问题:您如何更改用matplotlib绘制的图形的大小?

如何更改用matplotlib绘制的图形的大小?

How do you change the size of figure drawn with matplotlib?


回答 0

该图告诉您呼叫签名:

from matplotlib.pyplot import figure
figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')

figure(figsize=(1,1)) 会创建一个一英寸一英寸的图像,该图像将是80 x 80像素,除非您还指定了不同的dpi参数。

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.


回答 1

如果您已经创建了图形,则可以快速执行以下操作:

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

要将大小更改传播到现有的GUI窗口,请添加 forward=True

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

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)

回答 2

弃用说明:
根据官方Matplotlib指南pylab不再建议使用该模块。请考虑使用该matplotlib.pyplot模块,如该其他答案所述

以下似乎有效:

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

这使图形的宽度为5英寸,高度为10 英寸

然后,Figure类将其用作其参数之一的默认值。

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.


回答 3

使用plt.rcParams

如果您想在不使用图形环境的情况下更改大小,也可以使用此解决方法。因此,plt.plot()例如在使用时,可以设置宽度和高度的元组。

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

当您以内联方式绘制时(例如,使用IPython Notebook),这非常有用。正如@asamaier所注意的那样,最好不要将此语句放在import语句的同一单元格中。

转换为厘米

figsize元组接受英寸所以,如果你想将其设置成你必须2.54分他们厘米,看一下这个问题

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 @asamaier noticed is preferable to not put this statement in the same cell of the imports statements.

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 to this question.


回答 4

请尝试以下简单代码:

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

在绘制之前,需要设置图形尺寸。

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.


回答 5

如果您正在寻找一种方法来更改Pandas中的图形大小,可以执行例如:

df['some_column'].plot(figsize=(10, 5))

df熊猫数据框在哪里。或者,使用现有图形或轴

fig, ax = plt.subplots(figsize=(10,5))
df['some_column'].plot(ax=ax)

如果要更改默认设置,可以执行以下操作:

import matplotlib

matplotlib.rc('figure', figsize=(10, 5))

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. Or, to use existing figure or axes

fig, ax = plt.subplots(figsize=(10,5))
df['some_column'].plot(ax=ax)

If you want to change the default settings, you could do the following:

import matplotlib

matplotlib.rc('figure', figsize=(10, 5))

回答 6

Google中的第一个链接'matplotlib figure size'AdjustingImageSize页面的Google缓存)。

这是上一页的测试脚本。它创建test[1-3].png同一图像的不同大小的文件:

#!/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.

输出:

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.]

两个注意事项:

  1. 模块注释和实际输出不同。

  2. 通过此答案,可以轻松地将所有三个图像合并到一个图像文件中,以查看大小的差异。

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:

  1. The module comments and the actual output differ.

  2. This answer allows easily to combine all three images in one image file to see the difference in sizes.


回答 7

您可以简单地使用(来自matplotlib.figure.Figure):

fig.set_size_inches(width,height)

从Matplotlib 2.0.0开始,对画布的更改将立即可见,因为forward关键字默认为True

如果您只想更改宽度高度而不是两者,则可以使用

fig.set_figwidth(val) 要么 fig.set_figheight(val)

这些也将立即更新您的画布,但仅限于Matplotlib 2.2.0和更高版本。

对于较旧的版本

您需要forward=True明确指定以便实时更新比上面指定的版本更早的画布。请注意,在Matplotlib 1.5.0之前的版本中,set_figwidthand set_figheight函数不支持该forward参数。

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.

For Older Versions

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.


回答 8

import matplotlib.pyplot as plt
plt.figure(figsize=(20,10))
plt.plot(x,y) ## This is your plot
plt.show()

您还可以使用:

fig, ax = plt.subplots(figsize=(20, 10))
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))

回答 9

尝试注释掉该fig = ...

%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()

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()

回答 10

这对我来说很好:

from matplotlib import pyplot as plt

F = plt.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

这也可能会有所帮助:http : //matplotlib.1069221.n5.nabble.com/Resizing-figure-windows-td11424.html

This works well for me:

from matplotlib import pyplot as plt

F = plt.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


回答 11

要增加N倍的图形大小,您需要在pl.show()之前插入它:

N = 2
params = pl.gcf()
plSize = params.get_size_inches()
params.set_size_inches( (plSize[0]*N, plSize[1]*N) )

它也可以与ipython notebook一起很好地工作。

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.


回答 12

由于Matplotlib 本身无法使用公制,因此,如果要以合理的长度单位(例如厘米)指定图形的大小,则可以执行以下操作(来自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)

然后,您可以使用:

plt.figure(figsize=cm2inch(21, 29.7))

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))

回答 13

即使在绘制图形之后,这也会立即调整图形的大小(至少使用带有matplotlib 1.4.0的Qt4Agg / TkAgg-但不使用MacOSX-):

matplotlib.pyplot.get_current_fig_manager().resize(width_px, height_px)

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)

回答 14

概括和简化psihodelia的答案。如果您想将图形的当前大小更改一个因子sizefactor

import matplotlib.pyplot as plt

# here goes your code

fig_size = plt.gcf().get_size_inches() #Get current size
sizefactor = 0.8 #Set a zoom factor
# Modify the current size by the factor
plt.gcf().set_size_inches(sizefactor * fig_size) 

更改当前大小后,可能需要微调子图布局。您可以在图形窗口GUI中执行此操作,也可以通过命令subplots_adjust进行操作

例如,

plt.subplots_adjust(left=0.16, bottom=0.19, top=0.82)

Generalizing and simplifying psihodelia’s answer. If you want to change the current size of the figure by a factor sizefactor

import matplotlib.pyplot as plt

# here goes your code

fig_size = plt.gcf().get_size_inches() #Get current size
sizefactor = 0.8 #Set a zoom factor
# Modify the current size by the factor
plt.gcf().set_size_inches(sizefactor * fig_size) 

After changing the current size, it might occur that you have to fine tune the subplot layout. You can do that in the figure window GUI, or by means of the command subplots_adjust

For example,

plt.subplots_adjust(left=0.16, bottom=0.19, top=0.82)

回答 15

另一种选择是在matplotlib中使用rc()函数(单位为英寸)

import matplotlib
matplotlib.rc('figure', figsize=[10,5])

Another option, to use the rc() function in matplotlib (the unit is inch)

import matplotlib
matplotlib.rc('figure', figsize=[10,5])

回答 16

您可以通过直接更改图形尺寸

plt.set_figsize(figure=(10, 10))

You directly change the figure size by using

plt.set_figsize(figure=(10, 10))