使用matplotlib的imshow和scatter函数获取相同的子图尺寸

5 浏览
0 Comments

使用matplotlib的imshow和scatter函数获取相同的子图尺寸

我试图在同一张图中绘制一张图像(使用matplotlib.imshow)和一个散点图。在尝试时,图像的大小似乎比散点图小。以下是一个简单的示例代码:

import matplotlib.pyplot as plt
import numpy as np
image = np.random.randint(100,200,(200,200))
x = np.arange(0,10,0.1)
y = np.sin(x)
fig, (ax1, ax2) = plt.subplots(1,2)
ax1.imshow(image)
ax2.scatter(x,y)
plt.show()

这将得到以下的图像:

enter image description here

如何使这两个子图具有相同的高度?(我想也包括宽度)

我尝试了使用gridspec,如这个答案中所示:

fig=plt.figure()
gs=GridSpec(1,2)
ax1=fig.add_subplot(gs[0,0])
ax2=fig.add_subplot(gs[0,1])
ax1.imshow(image)
ax2.scatter(x,y)

但是这给出了相同的结果。我还尝试了手动调整子图大小:

fig = plt.figure()
ax1 = plt.axes([0.05,0.05,0.45,0.9])
ax2 = plt.axes([0.55,0.19,0.45,0.62])
ax1.imshow(image)
ax2.scatter(x,y)

通过试错,我可以使两个子图达到正确的大小,但是整体图像大小的任何更改都意味着子图将不再是相同的大小。

有没有一种方法可以在图中使imshowscatter图具有相同的大小,而不需要手动更改轴的大小?

我使用的是Python 2.7和matplotlib 2.0.0。

0