Plotly: 如何在保存图像后去除白色空间?

6

我有一个关于将 plotly 表格保存为图片的问题。我编写了以下代码:

import plotly.graph_objects as go

layout = go.Layout(autosize=True, margin={'l': 0, 'r': 0, 't': 0, 'b': 0})

fig = go.Figure(data=[go.Table(header=dict(values=['A Scores', 'B Scores']),
                           cells=dict(values=[[100, 90, 80, 90], [95, 85, 75, 95]]))
                  ], layout=layout)

fig.write_image("fig1.png", scale=5)

不幸的是,表格底部有一个很大的白色空白。

大白色空间

我能从图片中剪切它吗?高度设置不适用,因为表格可能有不同数量的行。


6
看起来这个问题在这里也有被讨论过(链接),但目前还没有得到答案。 - rpanai
1个回答

1

你可以通过设置单元格高度和整个图像高度来实现:

import plotly.graph_objects as go

CELL_HEIGHT = 30
a_scores = [100, 90, 80, 90]
b_scores = [95, 85, 75, 95]

layout = go.Layout(
    autosize=True, 
    margin={'l': 0, 'r': 0, 't': 0, 'b': 0}, 
    height=CELL_HEIGHT * (len(a_scores) + 1)
)

fig = go.Figure(
    data=[
        go.Table(
            header=dict(values=['A Scores', 'B Scores']), 
            cells=dict(values=[a_scores, b_scores], 
            height=CELL_HEIGHT)
        )
    ], 
    layout=layout
)

fig.write_image("fig1.png", scale=5)

完美裁剪的4行和标题表格

如果您想为标题设置不同的高度:

import plotly.graph_objects as go

CELL_HEIGHT = 30
HEADER_CELL_HEIGHT = 100
a_scores = [100, 90, 80, 90]
b_scores = [95, 85, 75, 95]

layout = go.Layout(
    autosize=True, 
    margin={'l': 0, 'r': 0, 't': 0, 'b': 0}, 
    height=CELL_HEIGHT * len(a_scores) + HEADER_CELL_HEIGHT
)

fig = go.Figure(
    data=[
        go.Table(
            header=dict(values=['A Scores', 'B Scores'], height=HEADER_CELL_HEIGHT), 
            cells=dict(values=[a_scores, b_scores], 
            height=CELL_HEIGHT)
        )
    ], 
    layout=layout
)

fig.write_image("fig1.png", scale=5)

4行和不同大小表头的表格完美裁剪

我尝试了不同的数据大小、表头单元格大小和单元格大小,它总是完美地裁剪。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接