You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用subplot_mosaic时子图比例意外改变的问题求助

使用subplot_mosaic时子图比例意外改变的问题求助

我现在想用subplot_mosaic来实现一组子图布局,需求是每一行里既有几个大尺寸的子图,又包含几排小尺寸的子图。我写了一个最小复现的示例代码,结果却遇到了子图比例意外偏差的问题——本来每一行的布局比例应该完全一致,但实际生成的图里,小图的尺寸明显不对。

我的示例代码如下:

import matplotlib.pyplot as plt

def test():

    fig = plt.figure(
                    layout="constrained", 
                     figsize = (20, 20)
                     )

    row = 3
    subcol = 3
    subrow = 3
    col = 1
    subfigs = fig.subfigures(nrows=row, ncols=col)
    axes = {}

    overall = ['A', 'B', 'C']
    names = [ ['a', *[str(i + j * subcol) for i in range(subcol)], 'b', 'c'] for j in range(subrow)]

    for i in range(row):

        subfig : plt.Figure = subfigs[i]

        mosaic = [[ overall[i] + name for name in namerow] for namerow in names]
        width_ratios = [ 1.0, 0.5, 0.5, 0.5, 1.0, 1.0]
        height_ratios = [ 1.0, 1.0, 1.0]

        axes |= subfig.subplot_mosaic(mosaic,  width_ratios=width_ratios, height_ratios=height_ratios)

        for ax_name in axes:

            axes[ax_name].set_title(ax_name)


    fig.savefig('test.png')

test()

运行这段代码后,我得到的结果图是这样的:

Empty plot showing the uneven grid

可以看到,三行主布局本应该有着完全一致的比例,但实际中小图的尺寸被意外调整了。而且这个问题的表现还会随着画布大小等参数变化,想请教一下有没有可靠的方法能避免这种情况?

备注:内容来源于stack exchange,提问作者RLLL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 11:54:33