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

如何移除动态Plotly表格下方的空白区域?

问题:移除Plotly表格图片下方的空白区域

我通过Pandas从SQL查询获取DataFrame,生成了一个动态Plotly表格,表格高度随数据量动态变化,未设置固定高度。现在需要将该表格以图片形式通过aiogram Telegram机器人发送,请问如何移除因未固定高度而出现的表格下方空白区域?

我的代码如下:

figure = go.Figure(data=[go.Table(
    columnwidth=[300, 200, 500, 500, 150, 400, 500, 150],
    header=dict(
        values=['<b>Date</b>', '<b>Time</b>', '<b>Client</b>', '<b>Service</b>', '<b>Price</b>', '<b>Tips</b>', '<b>Additional</b>', '<b>Work time</b>'],
        align=['center'],
        height=40
    ),
    cells=dict(
        values=dataframe.transpose().values.tolist(),
        align=['center'],
        height=30
    ),
)])
figure.update_layout(autosize=False, margin={'l': 0, 'r': 0, 't': 0, 'b': 0}, width=1280)
figure.write_image("db/records.png")

更新:dataframe.head().to_dict()结果

{'0': {0: '2022-10-24'}, '1': {0: '15:00'}, '2': {0: 'Bob'}, '3': {0: 'Radiator replacement'}, '4': {0: '16'}, '5': {0: '4'}, '6': {0: 'No'}, '7': {0: '2.0 h'}}

解决方案

问题根源是Plotly输出图片时默认会预留额外空白高度,哪怕设置了margin为0,也需要手动计算表格实际高度并指定给图表布局。

计算逻辑

表格总高度 = 表头高度 + 数据行数 × 每行单元格高度
从代码里可知,表头高度是40,每行单元格高度是30,直接用DataFrame的行数计算即可。

修改后的完整代码

import plotly.graph_objects as go

# 获取数据行数
row_count = len(dataframe)
# 计算表格实际总高度
total_height = 40 + row_count * 30

figure = go.Figure(data=[go.Table(
    columnwidth=[300, 200, 500, 500, 150, 400, 500, 150],
    header=dict(
        values=['<b>Date</b>', '<b>Time</b>', '<b>Client</b>', '<b>Service</b>', '<b>Price</b>', '<b>Tips</b>', '<b>Additional</b>', '<b>Work time</b>'],
        align=['center'],
        height=40
    ),
    cells=dict(
        values=dataframe.transpose().values.tolist(),
        align=['center'],
        height=30
    ),
)])
# 在布局中添加计算好的高度参数
figure.update_layout(autosize=False, margin={'l': 0, 'r': 0, 't': 0, 'b': 0}, width=1280, height=total_height)
figure.write_image("db/records.png")

这样设置后,Plotly会严格按照表格实际需要的高度生成图片,不会预留多余空白,发送到Telegram时就不会出现下方空白区域了。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:45:37