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

如何用Matplotlib生成上两面板下居中同尺寸的子图布局?

解决方案

原代码中底部子图D占据了整行的全部列宽,因此宽度是上方A、C子图的总和。要实现D与A、C尺寸相同且居中,可通过调整subplot_mosaic的布局结构和网格参数来实现:

修改后的代码如下:

import matplotlib.pyplot as plt
import numpy as np


# Helper function used for visualization in the following examples
def identify_axes(ax_dict, fontsize=48):
    """
    Helper to identify the Axes in the examples below.

    Draws the label in a large font in the center of the Axes.

    Parameters
    ----------
    ax_dict : dict[str, Axes]
        Mapping between the title / label and the Axes.
    fontsize : int, optional
        How big the label should be.
    """
    kw = dict(ha="center", va="center", fontsize=fontsize, color="darkgrey")
    for k, ax in ax_dict.items():
        ax.text(0.5, 0.5, k, transform=ax.transAxes, **kw)

# 采用三列布局,中间列作为占位符,通过gridspec参数控制尺寸
axd = plt.figure(layout="constrained").subplot_mosaic(
    """
    A . C
    . D .
    """,
    gridspec_kw={
        'width_ratios': [1, 0, 1],  # 中间列宽度设为0,消除多余空隙
        'height_ratios': [1, 1]     # 两行高度保持一致
    }
)
identify_axes(axd)
plt.show()

关键调整说明:

  • 布局字符串使用三列结构,A和C分别位于左右列,D位于中间列,.表示空的占位轴
  • gridspec_kw中width_ratios设为[1,0,1],确保左右列宽度一致,中间列宽度归零,避免出现空隙
  • height_ratios设为[1,1],保证上下两行的高度相同,使得所有子图的整体尺寸完全一致

内容的提问来源于stack exchange,提问作者TomCho

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 09:15:34