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


当前回答

概括和简化了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)

其他回答

试着注释一下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

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

您可以简单地使用(来自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参数。

如果已经创建了地物,可以使用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)

我总是使用以下模式:

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时,绘图将填充图形而无边框。