matplotlib调整子图尺寸,消除大图白边框

比较简单的方法是加一行:plt.tight_layout()

示例:

import matplotlib.gridspec as gridspec  # 用网格来创建子图
import matplotlib.pyplot as plt


def draw_pic():
    fig = plt.figure(figsize=(4, 6))  # 创建画布
    grid = gridspec.GridSpec(2, 3)  # 设定2行*3列的网格
    ax1 = fig.add_subplot(grid[0, :])  # 第一行的全部列都添加到ax1中
    ax1.plot([1, 2, 3], [1, 2, 3])  # 在ax1中绘图与操作,这都是这个ax的操作,不会影响全局
    ax2 = fig.add_subplot(grid[1, 0])  # 第二行,第1列
    ax2.plot([1, 2, 3], [1, 2, 3])
    ax3 = fig.add_subplot(grid[1, 2])  # 第二行,第3列
    ax3.plot([1, 2, 3], [1, 2, 3])
    return fig


if __name__ == '__main__':
    my_fig = draw_pic()
    my_fig.tight_layout()  # 调整尺寸
    my_fig.show()

如果需要加大图标题,这样会导致字与大图重叠,使用:plt.subplots_adjust()

import matplotlib.gridspec as gridspec  # 用网格来创建子图
import matplotlib.pyplot as plt


def draw_pic():
    fig = plt.figure(figsize=(4, 6))  # 创建画布
    grid = gridspec.GridSpec(2, 3)  # 设定2行*3列的网格
    ax1 = fig.add_subplot(grid[0, :])  # 第一行的全部列都添加到ax1中
    ax1.plot([1, 2, 3], [1, 2, 3])  # 在ax1中绘图与操作,这都是这个ax的操作,不会影响全局
    ax2 = fig.add_subplot(grid[1, 0])  # 第二行,第1列
    ax2.plot([1, 2, 3], [1, 2, 3])
    ax3 = fig.add_subplot(grid[1, 2])  # 第二行,第3列
    ax3.plot([1, 2, 3], [1, 2, 3])
    return fig


if __name__ == '__main__':
    my_fig = draw_pic()
    # 调整尺寸+标题
    my_fig.subplots_adjust(top=0.9)
    my_fig.suptitle("This is title")
    my_fig.show()

Guess you like

Origin blog.csdn.net/weixin_35757704/article/details/121715493