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

Viewed 1424

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)

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

big white space

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

1 Answers

You can do it by setting the cell height and the entire image height according to this cell height:

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 rows and header table perfectly cropped

If you want to give a different height to the headers:

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 rows and header of different size table perfectly cropped

I tried it with different data sizes, header cells size and cells size and it was always perfectly cropped.

Related