Plotly: How to remove white space after saving an image?

Gol*_*ter 6 python plotly

I have a question about saving plotly table as an image. I wrote the following code:

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)
Run Code Online (Sandbox Code Playgroud)

But unfortunately, there is a big white space at the bottom of the table.

大空白

Can I cut it from the image? The height setting doesn't fit because the table may have a different number of rows.

vin*_*zee 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)
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

4 行和不同尺寸表格的标题完美裁剪

我尝试使用不同的数据大小、标题单元格大小和单元格大小,并且它总是被完美裁剪。