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

Matplotlib savefig传入papertype参数触发弃用警告问题咨询

问题背景

正在生成系列图表计划整合制作为小册子,初始实现代码如下:

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

mosaic = """
        BC
        AA
        AA
        """

pp = PdfPages('/path/to/test.pdf')

for i in range(10):
    
    fig = plt.figure(figsize=(8.27, 11.69), facecolor='white')
    ax_dict = fig.subplot_mosaic(mosaic)
    
    ax = ax_dict['A']
    ax.set_facecolor('lightgrey')

    plt.savefig(pp, format='pdf', papertype='A4', bbox_inches='tight', pad_inches=.5)
    fig.clf()
    
pp.close()

运行代码时收到如下警告:

MatplotlibDeprecationWarning: savefig() got unexpected keyword argument "papertype" which is no longer supported as of 3.3 and will become an error two minor releases later plt.savefig(pp, format='pdf', papertype='A4', bbox_inches='tight', pad_inches=.5)

查阅Matplotlib 3.4.3版本官方API文档时,papertype仍被标注为可用参数,当前使用Matplotlib版本为3.4.3,需确认是否为参数使用场景错误。

问题原因

papertype参数的生效场景有严格限制:

  • 该参数是PDF后端的专属配置参数,仅当savefig直接写入本地PDF文件路径、未提前初始化PdfPages对象时,才会被正确识别处理。
  • 当savefig的写入目标是已经初始化完成的PdfPages实例时,PDF的页面尺寸、纸张类型等配置在PdfPages初始化阶段就已经确定,savefig阶段传入papertype属于无效传参,因此触发弃用警告,和版本新旧无关。

你在文档中查到的参数说明,对应的是直接输出PDF文件场景下的参数定义,不覆盖PdfPages写入的场景,不属于文档错误。

修正方法

二选一即可解决警告:

  • 方案1:直接删除savefig中的papertype='A4'参数。你的代码已经手动设置figsize=(8.27, 11.69),就是标准A4纸的尺寸,不需要额外指定纸张类型,输出的PDF页面大小完全符合A4要求。
  • 方案2:如果需要显式指定纸张类型,将papertype参数移到PdfPages初始化语句中传入,不要在savefig中传递,示例:
    # 初始化时指定纸张类型
    pp = PdfPages('/path/to/test.pdf', papertype='a4')
    
    后续savefig调用时不需要再传入papertype参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 17:21:34