是否可以更改 imshow matplotlib 可视化的宽度?

Ale*_*gur 2 python matplotlib

我想制作一个使用imshowin 的图形matplotlib,我可以有效地设置宽度和高度。我以为我可以figsize这样做,但它的表现就像我想象的那样。

例如,使用以下 MWE:

import matplotlib.pyplot as plt
import numpy as np

N = 100
width = 20
height = 20
Z = np.random.random((width,height))

G = np.zeros((width,height,3))

# Here we set the RGB for each pixel
G[Z>0.5] = [1,1,1]
G[Z<0.5] = [0,0,0]

plt.figure(figsize = (2, 5))
plt.imshow(G,interpolation='nearest')
plt.grid(False)
plt.show()
Run Code Online (Sandbox Code Playgroud)

这是我得到的:

在此输入图像描述

例如,如果我更改figsize = (2, 5)figsize = (2, 2),比例不会改变!

在尝试了几个不同的值之后,我认为这是因为图形被渲染为一个盒子而不是一个矩形:无论我设置什么,figsize各个矩阵条目都是一个常量盒子。

是否有一个命令可以用来告诉 matplotlib 扩展到 例如800x400px

tac*_*ell 7

默认行为imshow是将主机轴的纵横比设置为“相等”(即数据单元中的正方形是屏幕空间中的正方形)。如果您不关心这一点,只需将方面设置为“自动”即可。

import matplotlib.pyplot as plt
import numpy as np


N = 100
width = 20
height = 20
Z = np.random.random((width, height))

G = np.zeros((width, height, 3))

# Here we set the RGB for each pixel
G[Z > 0.5] = [1, 1, 1]
G[Z < 0.5] = [0, 0, 0]

fig, ax = plt.subplots(figsize=(2, 5))
ax.imshow(G, interpolation='nearest')
ax.set_aspect('auto')
plt.show()
Run Code Online (Sandbox Code Playgroud)