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

如何在保持figsize=(8,3)的前提下缩小适配Matplotlib子图?

问题解决:固定尺寸PDF中让直方图子图适配边界

核心需求

需将直方图保存为**固定尺寸(8,3)**的PDF,让子图完全适配页面边界,匹配其他表格的布局,但调整网格、图表大小后仍未解决。

修正后的实现方案

问题根源在于布局逻辑和保存时的边距控制,以下是两种可靠的修正方式:

方式1:面向对象API + 自动布局

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.backends.backend_pdf import PdfPages
import os

# 用os.path.join避免路径拼接的平台兼容问题
pdf_path = os.path.join(path, f"{Category}_{today}.pdf")

with PdfPages(pdf_path) as export_pdf:
    # 创建figure时启用自动布局,自动适配子图与标签空间
    fig = plt.figure(figsize=(8, 3), constrained_layout=True)
    gs = gridspec.GridSpec(1, 1, height_ratios=[1])
    ax0 = fig.add_subplot(gs[0])
    
    ax0.hist(uniqueData["Time per call"].values, edgecolor='black')
    ax0.set_xlabel('Minutes')
    ax0.set_ylabel('Frequency')
    ax0.set_title('Distribution Plot of time taken for 1 call (mins)')
    
    # 保存时消除所有额外边距
    export_pdf.savefig(fig, bbox_inches='tight', pad_inches=0)
    plt.close(fig)

方式2:Pyplot接口 + 手动布局压缩

import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import os

pdf_path = os.path.join(path, f"{Category}_{today}.pdf")

with PdfPages(pdf_path) as export_pdf:
    plt.figure(figsize=(8, 3))
    plt.hist(uniqueData["Time per call"].values, edgecolor='black')
    plt.xlabel('Minutes')
    plt.ylabel('Frequency')
    plt.title('Distribution Plot of time taken for 1 call (mins) for category: {}'.format(unique))
    
    # 强制压缩子图与figure的空白间距
    plt.tight_layout(pad=0)
    # 保存时裁剪所有冗余空白
    export_pdf.savefig(bbox_inches='tight', pad_inches=0)
    plt.close()

关键修改说明

  • constrained_layout=True:创建figure时启用,Matplotlib会自动计算子图、标签、标题的最优位置,避免内容重叠且最大化利用figure空间,比手动调整subplots_adjust更稳定。
  • tight_layout(pad=0):手动触发布局调整,pad=0将figure内的空白边距压缩至最小。
  • savefig(bbox_inches='tight', pad_inches=0):保存PDF时强制裁剪所有多余空白区域,确保子图边界完全匹配设定的figure尺寸。
  • 路径优化:用os.path.join替代硬编码反斜杠,解决跨平台路径兼容问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 10:42:51