Matplotlib:强制子图的大小(高度)相等?

Matplotlib: enforce equal size (height) of subplots?

我有一个包含三个子图的图形。第一个子图是图像 (imshow),而另外两个是分布 (plot)。

代码如下:

# collects data
imgdata = ...      # img of shape  (800, 1600, 3)    
x = ...            # one 1600-dimensional vector
y = ...            # one  800-dimensional vector

# create the figure 
f = plt.figure()    

# create subplots   
subplot_dim = (1, 3)
p_img = plt.subplot2grid(subplot_dim, (0, 0), aspect="auto")
p_x = plt.subplot2grid(subplot_dim, (0, 1), aspect="auto")
p_y = plt.subplot2grid(subplot_dim, (0, 2), aspect="auto")

p_img.imshow(imgdata, interpolation="None")
p_x.plot(x)         
p_y.plot(y)         


# save figure       
f.set_size_inches(21.0, 12.0)
f.savefig("some/path/image.pdf", dpi=80)

我的问题是,两个子图 p_xp_y 总是 的高度大于图像子图 p_img

因此,结果总是这样:

                  ###############   ###############   
                  #             #   #  *****      #
                  #        *****#   # *     *     #
###############   #     ***     #   # *      *    #
#             #   #    *        #   # *        *  #
#    image    #   #   *         #   #*           *#
#             #   #***          #   #*           *#
###############   ###############   ###############
     p_img              p_x               p_y

如何强制 p_imgp_x 的尺寸(或至少 高度)和 p_y?

编辑:这是一个简单的示例代码,它生成随机数据并使用plt.show()而不是保存图形。然而,在那里可以很容易地看到相同的行为:图像比其他子图小得多(高度):

from matplotlib import pyplot as plt 
from matplotlib import image as mpimg
import numpy as np

imgdata = np.random.rand(200, 400, 3)  
x = np.random.normal(loc=100.0, scale=20.0, size=400)
y = np.random.normal(loc=150.0, scale=15.0, size=200) 

# create the figure
f = plt.figure()

# create subplots
subplot_dim = (1, 3)
p_img = plt.subplot2grid(subplot_dim, (0, 0), aspect="auto")
p_x = plt.subplot2grid(subplot_dim, (0, 1), aspect="auto")
p_y = plt.subplot2grid(subplot_dim, (0, 2), aspect="auto")

p_img.imshow(imgdata, interpolation="None")
p_x.plot(x)
p_y.plot(y)


# save figure
plt.show()

你可以像这样在子图中直接指定它:

from matplotlib import pyplot as plt
from matplotlib import image as mpimg
import numpy as np

imgdata = np.random.rand(200, 400, 3)
x = np.random.normal(loc=100.0, scale=20.0, size=400)
y = np.random.normal(loc=150.0, scale=15.0, size=200)

# create the figure
f = plt.figure()

# create subplots
subplot_dim = (1, 3)
p_img = plt.subplot2grid(subplot_dim, (0, 0), aspect="auto")
p_x = plt.subplot2grid(subplot_dim, (0, 1), aspect="auto", adjustable='box-forced', sharex=p_img, sharey=p_img)
p_y = plt.subplot2grid(subplot_dim, (0, 2), aspect="auto", adjustable='box-forced', sharex=p_img, sharey=p_img)

p_img.imshow(imgdata, interpolation="None")
p_x.plot(x)
p_y.plot(y)

,结果是:

问题是您的数据没有相同的限制。因此,您必须使用 set_xlimset_ylim 进行调整。我还建议测试 sharey 的其他组合,因为它们可能会提供更好的结果。