【问题标题】:Plotly: How to remove white space after saving an image?Plotly:保存图像后如何删除空白?
【发布时间】:2020-12-01 14:27:39
【问题描述】:

我有一个关于将绘图表保存为图像的问题。我写了以下代码:

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)

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

我可以把它从图片上剪下来吗?高度设置不合适,因为表格可能有不同的行数。

【问题讨论】:

  • 看来这个问题也在here 讨论过。而且还没有答案。

标签: python plotly


【解决方案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)

如果你想给标题赋予不同的高度:

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)

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

【讨论】:

    猜你喜欢
    • 2012-08-03
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 2018-04-16
    • 2022-07-01
    • 1970-01-01
    相关资源
    最近更新 更多