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

如何下移Matplotlib绘图整体并消除底部空白区域?

问题

绘制的所有元素(热力图、标题、颜色条)均集中在图形窗口顶部,底部存在大量空白。尝试过fig.tight_layout()以及调整plt.figure函数的figsize参数,但底部空白比例仍未改变,相关代码如下:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid

def graphs():
    fig = plt.figure(figsize=(13.5, 6.8))
    Grid = AxesGrid(fig, 111, nrows_ncols=(1,3), axes_pad=0.2, share_all=False, label_mode='L', cbar_location="bottom", cbar_mode="single")

    Matrices = [np.random.randint(-100,10,(10,10)) for i in range(3)]
    M, m = np.max(Matrices), np.min(Matrices)

    for values, ax in zip(Matrices, Grid):

        ax.tick_params(top = True, bottom = False, labeltop = True, labelbottom = False)
        ax.xaxis.set_label_position('top')

        heatmap = ax.imshow(values, vmin=m, vmax=M, cmap='plasma')
        ax.set_xticks(np.arange(0,10), labels=list(np.arange(1,11)), fontsize=6)
        ax.set_xlabel('Arrival', fontweight='bold', fontsize=8)
        plt.setp(ax.get_xticklabels(), rotation=35, ha="center", rotation_mode=None)

        for l in range(len(values)):
            for c in range(len(values[l])):
                text = ax.text(c, l, values[l,c], ha="center", va="center", color='k', fontsize=6)

        ax.set_title('Gaps', fontweight='bold', fontsize=9)

    Grid[0].set_yticks(np.arange(0,10), labels=list(np.arange(1,11)), fontsize=6)
    Grid[0].set_ylabel('Depart', fontweight='bold', fontsize=8)

    for cax in Grid.cbar_axes:
        cax.remove()

    cbar = Grid[0].figure.colorbar(heatmap, ax = Grid, fraction=0.2, aspect=50, location='bottom', label='Gaps')
    plt.suptitle('Visualisation of different gaps', fontsize=15, fontweight='bold', y=0.97)
    plt.show()
解决方案

问题根源在于AxesGrid初始化时指定的cbar_location和cbar_mode参数会提前在底部预留colorbar空间,后续手动删除默认colorbar轴后,这部分预留空间就变成了无用的空白。结合布局调整可以彻底解决:

修改步骤

  1. 移除AxesGrid的colorbar预设参数:
    删除初始化时的cbar_location="bottom"和cbar_mode="single",避免提前预留不必要的底部空间。

  2. 手动调整整体布局:
    使用fig.subplots_adjust()设置bottom参数缩小底部空白,同时调整top参数确保标题和绘图元素不被截断。

  3. 适配标题位置:
    微调suptitle的y参数,让标题位置更协调。

修改后完整代码

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid

def graphs():
    # 可选:添加constrained_layout=True自动优化元素间距
    fig = plt.figure(figsize=(13.5, 6.8))
    # 移除cbar相关预设参数
    Grid = AxesGrid(fig, 111, nrows_ncols=(1,3), axes_pad=0.2, share_all=False, label_mode='L')

    Matrices = [np.random.randint(-100,10,(10,10)) for i in range(3)]
    M, m = np.max(Matrices), np.min(Matrices)

    for values, ax in zip(Matrices, Grid):
        ax.tick_params(top=True, bottom=False, labeltop=True, labelbottom=False)
        ax.xaxis.set_label_position('top')

        heatmap = ax.imshow(values, vmin=m, vmax=M, cmap='plasma')
        ax.set_xticks(np.arange(0,10), labels=list(np.arange(1,11)), fontsize=6)
        ax.set_xlabel('Arrival', fontweight='bold', fontsize=8)
        plt.setp(ax.get_xticklabels(), rotation=35, ha="center", rotation_mode=None)

        for l in range(len(values)):
            for c in range(len(values[l])):
                ax.text(c, l, values[l,c], ha="center", va="center", color='k', fontsize=6)

        ax.set_title('Gaps', fontweight='bold', fontsize=9)

    Grid[0].set_yticks(np.arange(0,10), labels=list(np.arange(1,11)), fontsize=6)
    Grid[0].set_ylabel('Depart', fontweight='bold', fontsize=8)

    # 无需再删除默认cbar轴(初始化时未创建)
    cbar = Grid[0].figure.colorbar(heatmap, ax=Grid, fraction=0.2, aspect=50, location='bottom', label='Gaps')
    
    # 调整布局:缩小底部空白,适配顶部标题
    fig.subplots_adjust(bottom=0.1, top=0.9)
    plt.suptitle('不同间隔的可视化', fontsize=15, fontweight='bold', y=0.98)
    plt.show()

graphs()

额外优化建议

如果希望更省心的布局管理,可以在创建figure时启用constrained_layout=True,它会自动调整所有元素的间距,减少手动调整的工作量:

fig = plt.figure(figsize=(13.5, 6.8), constrained_layout=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 02:35:28