我有一个包含三个子图的图形。第一个子图是图像 ( 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_x
, p_y
总是比图像子图的高度高 p_img
.
因此,结果总是这样的:
############### ###############
# # # ***** #
# *****# # * * #
############### # *** # # * * #
# # # * # # * * #
# image # # * # #* *#
# # #*** # #* *#
############### ############### ###############
p_img p_x p_y
我如何强制 p_img
的大小(或至少高度) , p_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_xlim
和 set_ylim
进行调整。我还建议测试 sharey
的其他组合,因为它们可能会提供更好的结果。
关于python - Matplotlib:强制子图的大小(高度)相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37767026/