Matplotlib:子图高度相同

问题描述 投票:0回答:2

在下面的示例中,如何将两个子图设置为相同的高度?

#minimal example
import matplotlib.pyplot as plt
import numpy as np
f, (ax1, ax2) = plt.subplots(1, 2)
im = np.random.random((100,100))
ax1.imshow(im)
ax1.set_xlim(0, im.shape[1])
ax1.set_ylim(0, im.shape[0])
x = np.arange(100)
ax2.plot(x, x**2)
python matplotlib subplot imshow
2个回答
2
投票

您可以使用

matplotlib.gridspec

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np

# Add subplots using gridspec instead of plt.subplots()
gs = gridspec.GridSpec(1,2, height_ratios=[1,1])
f = plt.figure()
ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])

im = np.random.random((100,100))
ax1.imshow(im)
ax1.set_xlim(0, im.shape[1])
ax1.set_ylim(0, im.shape[0])
x = np.arange(100)
ax2.plot(x, x**2)

产生如下输出:

Example image for same height using gridspec


0
投票

正如Wenzel Jakob所说,RickardSjogren的答案给了我同样的错误。

应赋予

GridSpec
的正确参数为
width_ratios
。为了使图像的高度相同,将
width_ratios
设置为图像的长宽比列表。

以下代码将正常工作:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np

im1 = np.random.normal(size=(100, 200))
im2 = np.random.normal(size=(200, 100))

aspect1 = im1.shape[1] / im1.shape[0]
aspect2 = im2.shape[1] / im2.shape[0]

gs = gridspec.GridSpec(1, 2, width_ratios=[aspect1, aspect2])

fig = plt.figure()
ax1 = plt.subplot(gs[0])
ax1.imshow(im1)
ax2 = plt.subplot(gs[1])
ax2.imshow(im2)

plt.show()

我得到的输出如下。

© www.soinside.com 2019 - 2024. All rights reserved.