【问题标题】:Insert shape in Dash DataTable在 Dash DataTable 中插入形状
【发布时间】:2021-01-18 16:38:28
【问题描述】:

我在破折号中有以下数据表。 生成此表的代码如下:

import dash
import dash_table
import pandas as pd

data = {'value':['very low','low','medium','high','very high'],'data':[1,3,5,7,10]}
df = pd.DataFrame(data)


app = dash.Dash(__name__)

app.layout = dash_table.DataTable(
    id='table',
    columns=[{"name": i, "id": i} for i in df.columns],
    data=df.to_dict('records'),
)

if __name__ == '__main__':
    app.run_server(debug=True)

但我想生成下表。我如何使用破折号来做到这一点?指示列是一个基于比例颜色编码的形状(例如,5 是中等的,因此 yellow/amber,高于 5 的值从 greendark green。类似地,低于 5 的值从 @987654329 @到red

【问题讨论】:

    标签: python pandas datatables plotly-dash


    【解决方案1】:

    感谢 Eduardo 在 plotly 社区论坛上,我了解到我们现在可以将 html 内容用于 DataTableplotly forum threadgithub pull request)的 Markdown 单元格。

    这允许我们做这样的事情:

    import dash
    import dash_html_components as html
    import dash_table
    import pandas as pd
    
    
    def get_svg_arrow(val):
        if val > 7:
            fill = "green"
        elif val > 5:
            fill = "blue"
        elif val == 5:
            fill = "yellow"
        elif val >= 3:
            fill = "orange"
        else:
            fill = "red"
    
        if val >= 5:
            path = f'<path d="M19.5 11L26 11L13 -1.1365e-06L7.97623e-09 11L6.5 11L6.5 22L19.5 22L19.5 11Z" fill="{fill}"/>'
        else:
            path = (
                f'<path d="M6.5 11H0L13 22L26 11L19.5 11V0L6.5 0L6.5 11Z" fill="{fill}"/>'
            )
    
        return f'<svg width="26" height="22" viewBox="0 0 26 22" fill="none" xmlns="http://www.w3.org/2000/svg">{path}</svg>'
    
    
    values = [1, 3, 5, 7, 10]
    data = {
        "value": ["very low", "low", "medium", "high", "very high"],
        "indicator": [get_svg_arrow(val) for val in values],
        "data": values,
    }
    
    df = pd.DataFrame(data)
    
    app = dash.Dash(__name__)
    
    app.layout = html.Div(
        [
            dash_table.DataTable(
                css=[dict(selector="p", rule="margin: 0px; text-align: center")],
                data=df.to_dict("records"),
                style_cell={"textAlign": "center"},
                columns=[
                    {"name": col, "id": col, "presentation": "markdown"}
                    if col == "indicator"
                    else {"name": col, "id": col}
                    for col in df.columns
                ],
                markdown_options={"html": True},
            )
        ]
    )
    
    if __name__ == "__main__":
        app.run_server()
    

    所以上面代码的想法是根据数据动态创建一个带有填充颜色的箭头svg。

    为了创建 svg 箭头,我使用了矢量绘图程序并导出为 svg,但如果您愿意,可以手动构建路径。

    结果

    【讨论】:

    • 非常感谢您来到这里并在找到答案后发布解决方案。我只是通过在我的仪表板应用程序中对我的数据值进行颜色编码来规避这一点;您的解决方案很有帮助,我可以将其添加为我们的企业应用程序的增强功能。非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 2011-06-11
    • 2011-08-10
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多