[英]I can make my scatterplot, but I can not draw my line with matplotlib in the same figure
[英]How can I make image and scatterplot the same height?
我正在绘制两个不同的子图。 一个是图像,另一个是散点图。
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()
问题是,当我绘制它们时,它们具有不同的高度。 我怎样才能使高度相同?
寻找设置高度matplotlib不会给出合适的结果。
您需要在imshow
调用中添加关键字aspect='auto'
。 所以看起来应该是这样的:
fig.add_subplot(1, 2, 1).imshow(image, cmap=cm.Greys_r, aspect='auto')
从文档:
方面:['auto'| '相等'| 标量],可选,默认值:无
如果是“自动”,则更改图像宽高比以匹配轴的宽高比。
如果“相等”且范围为“无”,则更改轴纵横比以匹配图像的纵横比。 如果extent不是None,则更改轴纵横比以匹配范围。
如果为None,则默认为rc image.aspect值。
除了@jure设置aspect
的答案(你可能也想尝试equal
而不是auto
,因为auto
不保证两个图看起来一样),你还需要确保xlim
和ylim
是相同的在两个子图之间,因为它目前看起来像imshow
的x
和y
范围都远远超出散点图的范围。
此外,在转换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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.