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

Python中如何将Dataframe完整保存为表格图片?

解决Plotly Table保存DataFrame所有行的问题

我想要在Python中将Dataframe保存为表格图片。参考Plotly官方文档实现时,仅能保存数据集的前几行而非全部,示例截图见保存不全的表格截图。请问是否有办法保存所有行?使用的代码如下:

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_usa_states.csv')

fig = go.Figure(data=[go.Table(
    header=dict(values=list(df.columns),
                fill_color='paleturquoise',
                align='left'),
    cells=dict(values=[df.Rank, df.State, df.Postal, df.Population],
               fill_color='lavender',
               align='left'))
])

fig.write_image('image.png',scale=10)

Plotly的Table组件默认会截断超出默认画布高度的内容,要保存所有行,只需手动设置图表高度,让所有行都能容纳进去。

修改后的代码如下:

import pandas as pd
import plotly.graph_objects as go

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_usa_states.csv')

# 计算所需高度:每行预估40像素,表头占50像素
row_height = 40
header_height = 50
total_height = header_height + len(df) * row_height

fig = go.Figure(data=[go.Table(
    header=dict(values=list(df.columns),
                fill_color='paleturquoise',
                align='left'),
    cells=dict(values=[df.Rank, df.State, df.Postal, df.Population],
               fill_color='lavender',
               align='left'))
])

# 设置图表高度以容纳所有行
fig.update_layout(height=total_height)

fig.write_image('full_table.png', scale=10)

说明

  • 通过总行数结合预估的行高、表头高度计算出总画布高度,确保所有行都能显示。
  • row_height可根据需求调整,让表格显示更美观。
  • scale参数保持不变,保证生成图片的清晰度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 08:02:40