【问题标题】:Python Plotly: autosize table plotPython Plotly:自动调整表格图
【发布时间】:2018-01-12 09:39:24
【问题描述】:

我正在使用 Plotly 绘制不同大小的表格,我想将其导出为图像。但是,绘图的大小不会随表格大小自动缩放,导致图像中只显示表格的一部分(或者如果我将绘图大小设置得太大,则会出现很多空白)。我知道我可以使布局的高度取决于行数,但这并不能解决问题,因为每行占用的空间也取决于实际的表格内容(例如,大字符串将需要更多空间)。

import pandas as pd
import plotly.graph_objs as go
import plotly.offline as py
py.offline.init_notebook_mode()
import numpy as np

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

trace = go.Table(
    header=dict(values=df.columns,
                fill = dict(color='#C2D4FF'),
                align = ['left'] * 5),
    cells=dict(values=[df.A, df.B, df.C, df.D],
               fill = dict(color='#F5F8FF'),
               align = ['left'] * 5))
layout = dict(autosize=True)
fig = go.Figure(data=[trace], layout=layout)

py.iplot(fig, show_link=False)

example of image export

提前致谢。

【问题讨论】:

  • 这段代码为我生成了一个空白图。这可能是一个 plotly/Jupyter 笔记本错误。但是,情节页面中的演示正确地绘制了......这段代码在 Jupyter 中为您创建了一个表?
  • 是的,它也在一个全新的笔记本中,没有加载任何其他内容。 Plotly 版本是 2.2.3,他们最近更新了很多,也许这会有所不同?
  • 无论如何,Plotly 本身的以下示例说明了同一点:plot.ly/python/table(第三个示例“Pandas Dataframe”)

标签: python python-3.x pandas plotly


【解决方案1】:

这绝不是一个完美的解决方案,参数需要根据字体大小、列数和输入字符串的长度进行调整。但它确实有效。

def calc_table_height(df, base=208, height_per_row=20, char_limit=30, height_padding=16.5):
    '''
    df: The dataframe with only the columns you want to plot
    base: The base height of the table (header without any rows)
    height_per_row: The height that one row requires
    char_limit: If the length of a value crosses this limit, the row's height needs to be expanded to fit the value
    height_padding: Extra height in a row when a length of value exceeds char_limit
    '''
    total_height = 0 + base
    for x in range(df.shape[0]):
        total_height += height_per_row
    for y in range(df.shape[1]):
        if len(str(df.iloc[x][y])) > char_limit:
            total_height += height_padding
    return total_height

如果您的font_size 与默认值不同,或者如果您更改了默认值margin,您可能需要尝试其他功能。此外,函数的 char_limit 参数是另一个弱点,因为某些字符比其他字符占用更多空间,大写字符占用更多空间,并且单个单词如果 long 可以强制扩展一行。如果数量或列数较少,也应该增加它,反之亦然。该函数以 4 个表列(this question)为基准编写。

定义函数后的代码

import pandas as pd
import plotly.graph_objs as go
import plotly.offline as py
py.offline.init_notebook_mode()
import numpy as np

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

trace = go.Table(
    header=dict(values=df.columns,
                fill = dict(color='#C2D4FF'),
                align = ['left'] * 5),
    cells=dict(values=[df.A, df.B, df.C, df.D],
               fill = dict(color='#F5F8FF'),
               align = ['left'] * 5))
layout = dict(height=calc_table_height(df))                #This is changed
fig = go.Figure(data=[trace], layout=layout)

py.iplot(fig, show_link=False)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-30
    • 2012-09-05
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-26
    相关资源
    最近更新 更多