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

如何在Python中将Seaborn风格DataFrame生成的表格保存到PDF

解决方案:保存带Seaborn渐变样式的DataFrame表格到PDF/图片

你的问题核心在于:原plot函数生成的是Pandas的Styler对象(而非Matplotlib的Figure),所以无法直接用PdfPages.savefig()保存。下面提供两种可靠的实现方案:

方法一:用WeasyPrint将HTML表格转多页PDF

这种方法直接利用Styler的HTML渲染能力转换为PDF,能完美保留渐变样式,步骤如下:

  1. 先修改函数,返回Styler对象(而非直接display):
import seaborn as sns
import pandas as pd

def get_styled_table(grid):
    cmap = sns.light_palette("red", as_cmap=True)
    df = pd.DataFrame(grid)
    return df.style.background_gradient(cmap=cmap, axis=None)
  1. 安装WeasyPrint依赖:
pip install weasyprint
  1. 批量生成表格并保存为多页PDF:
from weasyprint import HTML

# 示例:多个表格数据集
table_datasets = [
    [[1, 2, 3], [4, 5, 6]],
    [[7, 8, 9], [10, 11, 12]],
    [[13, 14, 15], [16, 17, 18]]
]

# 拼接所有表格的HTML,添加分页符
html_content = "<html><body>"
for data in table_datasets:
    styled_table = get_styled_table(data)
    html_content += styled_table.render() + '<div style="page-break-after: always;"></div>'
html_content += "</body></html>"

# 保存为PDF
HTML(string=html_content).write_pdf("styled_tables.pdf")

方法二:用Matplotlib+ImgKit转图片后保存PDF

如果需要沿用Matplotlib的PdfPages流程,可先将Styler转成图片,再添加到PDF中:

  1. 安装依赖:
pip install imgkit

同时需要安装wkhtmltopdf工具,并记住其安装路径。

  1. 实现代码:
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import imgkit
import io

# 配置wkhtmltopdf路径(根据自己的系统调整)
config = imgkit.config(wkhtmltopdf=r"C:\Program Files\wkhtmltopdf\bin\wkhtmltoimage.exe")

pdf = PdfPages("styled_tables_matplotlib.pdf")

for data in table_datasets:
    styled_table = get_styled_table(data)
    # 将Styler转成PNG图片
    img_bytes = styled_table.to_image(format="png", config=config)
    # 加载图片到Matplotlib Figure
    fig, ax = plt.subplots(figsize=(8, 2))
    ax.imshow(plt.imread(io.BytesIO(img_bytes)))
    ax.axis("off")  # 隐藏坐标轴
    pdf.savefig(fig, bbox_inches="tight")
    plt.close(fig)

pdf.close()

保存为单张PNG/JPG

如果要把所有表格放在同一张图片里:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=len(table_datasets), ncols=1, figsize=(8, 3*len(table_datasets)))

for idx, data in enumerate(table_datasets):
    styled_table = get_styled_table(data)
    img_bytes = styled_table.to_image(format="png", config=config)
    axes[idx].imshow(plt.imread(io.BytesIO(img_bytes)))
    axes[idx].axis("off")

plt.tight_layout()
plt.savefig("all_styled_tables.png", dpi=300, bbox_inches="tight")
plt.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 17:24:26