gpt4 book ai didi

matplotlib - 在matplotlib中创建多个大小不等的列和行

转载 作者:行者123 更新时间:2023-12-04 17:43:28 25 4
gpt4 key购买 nike

我需要在 matplotlib 中创建多个大小不等的列和行。这是一个示例代码:

a = np.random.rand(20, 20)
b = np.random.rand(20, 5)
c = np.random.rand(5, 20)
d = np.random.rand(5,5)
arrays = [a,b,c,d]
fig, axs = plt.subplots(2, 2, sharex='col', sharey= 'row', figsize=(10,10))
for ax, ar in zip(axs.flatten(), arrays):
ax.imshow(ar)

但是,我得到了这个结果。

python output

右列第一行和第二行的图像宽度不等,我希望它们相等(基本上缩小右下角的图像以与其他图像具有相同的比例)。我对此进行了大量研究,但似乎没有任何效果。我试过 tight_layout() 和其他一些格式化技巧,但都无济于事......

最佳答案

您可以使用 gridspec 的 height_ratioswidth_ratios 参数来设置子图应占据的所需比例。

在这种情况下,由于对称性,这只是形状,例如b.

import numpy as np
import matplotlib.pyplot as plt

a = np.random.rand(20, 20)
b = np.random.rand(20, 5)
c = np.random.rand(5, 20)
d = np.random.rand(5,5)
arrays = [a,b,c,d]
fig, axs = plt.subplots(2, 2, sharex='col', sharey= 'row', figsize=(10,10),
gridspec_kw={"height_ratios" : b.shape,
"width_ratios" : b.shape})
for ax, ar in zip(axs.flatten(), arrays):
ax.imshow(ar)

plt.show()

enter image description here

或者,更一般地说,

gridspec_kw={"height_ratios" : [a.shape[0], c.shape[0]], 
"width_ratios" : [a.shape[1], b.shape[1]]}

关于matplotlib - 在matplotlib中创建多个大小不等的列和行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53311865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com