如何使图像和散点图具有相同的高度?

2024-06-26 01:39:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在画两个不同的副图。一个是图像,另一个是散点图。你知道吗

fig = plt.figure(figsize=(16, 8))

# here I am drawing a greyscale image
image = img.imread(file_name)
fig.add_subplot(1, 2, 1).imshow(image, cmap=cm.Greys_r)
fig.tight_layout()
plt.axis('off')

# and here I am drawing a scatterplot based on this image.
X, Y = image.shape
x, y = np.nonzero(image)
fig.add_subplot(1, 2, 2).scatter(y - Y, -x)
fig.tight_layout()

问题是当我画它们的时候,它们有不同的高度。我怎样才能使高度相同?enter image description here

查找设置高度matplotlib不会给出合适的结果。你知道吗


Tags: 图像imageadd高度herefigpltam
2条回答

您需要将关键字aspect='auto'添加到imshow调用中。所以应该是这样的:

fig.add_subplot(1, 2, 1).imshow(image, cmap=cm.Greys_r, aspect='auto')

根据文件:

aspect : [‘auto’ | ‘equal’ | scalar], optional, default: None

If ‘auto’, changes the image aspect ratio to match that of the axes.

If ‘equal’, and extent is None, changes the axes aspect ratio to match that of the image. If extent is not None, the axes aspect ratio is changed to match that of the extent.

If None, default to rc image.aspect value.

除了@jure关于设置aspect的回答(您可能还想尝试equal而不是auto,因为auto不能保证两个图看起来相同),您还需要确保两个子图之间的xlimylim是相同的,因为它现在看起来像是xy范围在imshow中延伸得远远超出了散点图的范围。你知道吗

另外,在变换y和x坐标时,需要将范围设置为-X, 0-Y, 0

试试这个:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.image as img
import matplotlib.cm as cm


fig = plt.figure(figsize=(16, 8))

# here I am drawing a greyscale image
image = img.imread(filename)
ax1=fig.add_subplot(1, 2, 1, aspect='equal')
ax1.imshow(image, cmap=cm.Greys_r)
fig.tight_layout()
plt.axis('off')

# and here I am drawing a scatterplot based on this image.
X, Y = image.shape
x, y = np.nonzero(image)
ax2=fig.add_subplot(1, 2, 2, aspect='equal')
ax2.scatter(y - Y, -x, s=1, linewidths=0)
ax2.set_xlim(-Y, 0)
ax2.set_ylim(-X, 0)
fig.tight_layout()

plt.show()

enter image description here

相关问题 更多 >