You need to enable JavaScript to run this app. 使用PdfPages导出pivot table循环绘图时PDF无图的解决方法咨询
优惠活动
大模型
产品
解决方案
定价
更多

使用PdfPages导出pivot table循环绘图时PDF无图的解决方法咨询

问题原因
  • 缺少依赖导入:原代码直接调用plt.figure()但没有导入matplotlib.pyplot,会先触发导入报错
  • 绘图对象不匹配:pandas的DataFrame.plot()方法默认会自动创建新的画布对象,你提前声明的fig是空画布,最终保存的是空内容,核心问题是保存的画布和实际绘制了图表的画布不匹配
  • 冗余初始化:开头创建的pdf实例没有实际使用,属于无效代码
修复方案

修改逻辑为保证保存的画布就是实际绘制了内容的画布即可,以下是可直接运行的修复代码:

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

titanic = sns.load_dataset('titanic')

with PdfPages("seaborn.pdf") as export_pdf:
    s = ['embark_town', 'class', 'embarked']
    for i in s:
        # 直接获取pandas绘图返回的坐标轴对象,再取对应画布保存
        ax = titanic.pivot_table(values='fare', columns = i, index='sex', aggfunc='sum').plot(figsize=(10,5))
        export_pdf.savefig(ax.figure, bbox_inches='tight')
        # 关闭当前画布避免图表重叠、减少内存占用
        plt.close()

如果要沿用你原来提前创建画布的写法,也可以手动指定绘图的坐标轴对象:

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

titanic = sns.load_dataset('titanic')

with PdfPages("seaborn.pdf") as export_pdf:
    s = ['embark_town', 'class', 'embarked']
    for i in s:
        fig, ax = plt.subplots(figsize = [10, 5])
        # 给plot方法传入ax参数,指定把图画到提前创建的子图上
        titanic.pivot_table(values='fare', columns = i, index='sex', aggfunc='sum').plot(ax=ax)
        export_pdf.savefig(fig, bbox_inches='tight')
        plt.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 14:51:01