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


折旧说明:根据Matplotlib官方指南,不再建议使用pylab模块。请考虑改用matplotlib.pyplot模块,如另一个答案所述。

以下方法似乎有效:

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

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

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

谷歌中“matplotlib图形大小”的第一个链接是调整图像大小(页面的谷歌缓存)。

这是上面页面中的测试脚本。它创建同一图像的不同大小的测试[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.]

两个注意事项:

模块注释和实际输出不同。这个答案允许轻松地将所有三个图像组合在一个图像文件中,以查看大小的差异。

图告诉您通话签名:

from matplotlib.pyplot import figure

figure(figsize=(8, 6), dpi=80)

图(figsize=(1,1))将创建一个一英寸一英寸的图像,除非您也给出了不同的dpi参数,否则它将是80x80像素。

如果已经创建了地物,可以使用figure.set_size_inches调整地物大小:

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)

此外,正如Erik Shilts在评论中提到的,您还可以使用figure.set_dpi来“设置图形的分辨率,单位为每英寸点数”

fig.set_dpi(100)

试着注释一下fig=。。。线

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

这对我来说很好:

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

此论坛帖子也可能有帮助:调整图形窗口的大小

这将在绘制图形后立即调整图形大小(至少使用Qt4Agg/TkAgg,但不使用Mac OS X和Matplotlib 1.4.0):

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

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

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

其中df是Pandas数据帧。或者,要使用现有图形或轴:

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

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

import matplotlib

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

有关详细信息,请查看文档:pd.DataFrame.plot。

使用plt.rcParams

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

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

这在内联绘图时非常有用(例如,使用IPython Notebook)。正如我们所注意到的,最好不要将此语句放在imports语句的同一单元格中。

要将后续绘图的全局地物尺寸重置回默认值,请执行以下操作:

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

转换为厘米

figsize元组接受英寸,因此如果要将其设置为厘米,则必须将其除以2.54。看看这个问题。

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

fig.set_size_inches(width,height)

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

如果只想更改宽度或高度,而不是同时更改两者,可以使用

图set_figwidth(val)或图set_feight(val)

这些也会立即更新画布,但仅限于Matplotlib 2.2.0及更新版本。

对于旧版本

您需要显式指定forward=True,以便在比上面指定的更早的版本中实时更新画布。注意,在Matplotlib 1.5.0之前的版本中,set_figwidth和set_figeight函数不支持forward参数。

概括和简化了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中或通过命令sublots_adjust执行此操作

例如

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

我总是使用以下模式:

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)

使用此示例,您可以设置以英寸或毫米为单位的图形尺寸。将constrained_layout设置为True时,绘图将填充图形而无边框。

以像素为单位设置精确图像大小的不同方法的比较

这个答案将集中于:

savefig:如何保存到文件,而不仅仅显示在屏幕上设置像素大小

下面是我尝试过的一些方法的快速比较,这些方法的图像显示了给出的结果。

当前状态总结:事情很混乱,我不确定这是否是一个根本的限制,或者用例是否没有得到开发人员的足够关注。我很难找到关于这一点的上游讨论。

不尝试设置图像尺寸的基线示例

只是为了有一个比较点:

基本.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

fig, ax = plt.subplots()
print('fig.dpi = {}'.format(fig.dpi))
print('fig.get_size_inches() = ' + str(fig.get_size_inches())
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig('base.png', format='png')

Run:

./base.py
identify base.png

输出:

fig.dpi = 100.0
fig.get_size_inches() = [6.4 4.8]
base.png PNG 640x480 640x480+0+0 8-bit sRGB 13064B 0.000u 0:00.000

到目前为止,我最好的方法是:plt.savefig(dpi=h/fig.get_size_inches()[1]仅高度控制

我想这是我大部分时间都会做的事情,因为它很简单,而且规模很大:

获取大小.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

height = int(sys.argv[1])
fig, ax = plt.subplots()
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
    'get_size.png',
    format='png',
    dpi=height/fig.get_size_inches()[1]
)

Run:

./get_size.py 431

输出:

get_size.png PNG 574x431 574x431+0+0 8-bit sRGB 10058B 0.000u 0:00.000

and

./get_size.py 1293

输出:

main.png PNG 1724x1293 1724x1293+0+0 8-bit sRGB 46709B 0.000u 0:00.000

我倾向于只设置高度,因为我通常最关心的是图像在文本中间会占据多少垂直空间。

plt.savefig(bbox_inches='ight'更改图像大小

我总是觉得图像周围有太多空白,并倾向于从以下位置添加bbox_inches='ight':删除已保存图像周围的空白

然而,这是通过裁剪图像来实现的,并且您无法获得所需的大小。

相反,在同一问题中提出的另一种方法似乎很有效:

plt.tight_layout(pad=1)
plt.savefig(...

这给出了高度等于431:

固定高度、set_aspect、自动调整宽度和小边距

嗯,set_aspect又把事情搞砸了,并阻止plt.tight_layout实际删除边距。。。这是一个重要的用例,我还没有很好的解决方案。

问:如何在Matplotlib中获得固定的像素高度、固定的数据x/y纵横比并自动删除水平空白边距?

plt.savefig(dpi=h/图get_size_inches()[1]+宽度控制

如果你真的需要一个除高度外的特定宽度,这似乎可以:

宽度.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

h = int(sys.argv[1])
w = int(sys.argv[2])
fig, ax = plt.subplots()
wi, hi = fig.get_size_inches()
fig.set_size_inches(hi*(w/h), hi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
    'width.png',
    format='png',
    dpi=h/hi
)

Run:

./width.py 431 869

输出:

width.png PNG 869x431 869x431+0+0 8-bit sRGB 10965B 0.000u 0:00.000

对于小宽度:

./width.py 431 869

输出:

width.png PNG 211x431 211x431+0+0 8-bit sRGB 6949B 0.000u 0:00.000

因此,字体的缩放似乎是正确的,我们只是在非常小的宽度上遇到了一些麻烦,标签被切掉了,例如左上角的100。

我设法通过删除保存图像周围的空白来解决这些问题

plt.tight_layout(pad=1)

其给出:

width.png PNG 211x431 211x431+0+0 8-bit sRGB 7134B 0.000u 0:00.000

从这里,我们还可以看到,紧身布局删除了图像顶部的大量空白,所以我通常总是使用它。

修正了fig.set_size_inches和plt.savefig上的魔法基础高度、dpi(dpi=缩放

我认为这相当于以下所述的方法:https://stackoverflow.com/a/13714720/895245

魔法.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

magic_height = 300
w = int(sys.argv[1])
h = int(sys.argv[2])
dpi = 80
fig, ax = plt.subplots(dpi=dpi)
fig.set_size_inches(magic_height*w/(h*dpi), magic_height/dpi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
    'magic.png',
    format='png',
    dpi=h/magic_height*dpi,
)

Run:

./magic.py 431 231

输出:

magic.png PNG 431x231 431x231+0+0 8-bit sRGB 7923B 0.000u 0:00.000

看看它的规模是否很好:

./magic.py 1291 693

输出:

magic.png PNG 1291x693 1291x693+0+0 8-bit sRGB 25013B 0.000u 0:00.000

所以我们看到这种方法也很有效。我唯一的问题是必须设置magic_height参数或等效参数。

固定DPI+set_size_inches

这种方法给出了一个稍微错误的像素大小,这使得很难无缝地缩放所有内容。

set_size_inches.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

w = int(sys.argv[1])
h = int(sys.argv[2])
fig, ax = plt.subplots()
fig.set_size_inches(w/fig.dpi, h/fig.dpi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(
    0,
    60.,
    'Hello',
    # Keep font size fixed independently of DPI.
    # https://stackoverflow.com/questions/39395616/matplotlib-change-figsize-but-keep-fontsize-constant
    fontdict=dict(size=10*h/fig.dpi),
)
plt.savefig(
    'set_size_inches.png',
    format='png',
)

Run:

./set_size_inches.py 431 231

输出:

set_size_inches.png PNG 430x231 430x231+0+0 8-bit sRGB 8078B 0.000u 0:00.000

因此高度稍有偏差,图像:

如果我将其放大3倍,像素大小也是正确的:

./set_size_inches.py 1291 693

输出:

set_size_inches.png PNG 1291x693 1291x693+0+0 8-bit sRGB 19798B 0.000u 0:00.000

然而,我们从中了解到,为了使这种方法能够很好地缩放,您需要使每个DPI相关设置与英寸大小成比例。

在前面的示例中,我们只使“Hello”文本成比例,并且它的高度保持在60到80之间,正如我们预期的那样。但我们没有这么做的一切看起来都很小,包括:

轴的线宽刻度标记点标记

SVG

我找不到如何为SVG图像设置它,我的方法只适用于PNG,例如:

获取大小_版本.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

height = int(sys.argv[1])
fig, ax = plt.subplots()
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
    'get_size_svg.svg',
    format='svg',
    dpi=height/fig.get_size_inches()[1]
)

Run:

./get_size_svg.py 431

生成的输出包含:

<svg height="345.6pt" version="1.1" viewBox="0 0 460.8 345.6" width="460.8pt"

并且identify表示:

get_size_svg.svg SVG 614x461 614x461+0+0 8-bit sRGB 17094B 0.000u 0:00.000

如果我在Chromium 86中打开它,浏览器调试工具鼠标图像悬停确认高度为460.79。

当然,由于SVG是一种矢量格式,因此理论上一切都应该缩放,因此您可以转换为任何固定大小的格式而不损失分辨率,例如:

inkscape -h 431 get_size_svg.svg -b FFF -e get_size_svg.png

给出了准确的高度:

我在这里使用Inkscape而不是ImageMagick的转换,因为您还需要使用-desity来使用ImageMagick调整SVG的大小:

https://superuser.com/questions/598849/imagemagick-convert-how-to-produce-sharp-resized-png-files-from-svg-files/1602059#1602059如何使用ImageMagick将SVG转换为PNG?

在HTML上设置<img height=“”也应该只适用于浏览器。

它在matplotlib 3.2.2上进行了测试。