【问题标题】:Colour Plotly table based on value with index基于索引值的颜色绘图表
【发布时间】:2021-07-21 05:25:22
【问题描述】:

我有一个数据框

如何将其绘制为 Plotly 表,根据单元格值为其单元格着色,应将 1 替换为绿色,将 0 替换为灰色。 此外,在绘制表格时,列名和行索引应保持在表格中,不带颜色。

结果表应该是

上面的可视化可以使用 pandas 风格的配置来实现,但是我如何在 Plotly-Dash 中实现同样的效果

这里提供的例子https://plotly.com/python/table/#cell-color-based-on-variable, 不显示如何在不着色的情况下保留行和列索引名称/值

【问题讨论】:

    标签: pandas plotly plotly-dash


    【解决方案1】:
    • 它确实包含在 plotly table pandas 文档中
    • 只需要扩展以在提供给 header* 和 cells 的数据中包含索引
    • 加上一个符合您的样式要求的简单颜色矩阵
    import pandas as pd
    import numpy as np
    import plotly.graph_objects as go
    
    df = pd.DataFrame(
        {
            **{"index": [f"a{i+1}" for i in range(3)]},
            **{
                d: np.random.randint(0, 2, 3)
                for d in pd.date_range("18-jul-2021", periods=4)
            },
        }
    ).set_index("index")
    
    fig = go.Figure(
        go.Table(
            header={"values": [df.index.name] + df.columns.tolist()},
            cells=dict(
                values=df.reset_index().T.values,
                fill_color=np.select(
                    [df.reset_index().T.values == 1, df.reset_index().T.values == 0],
                    ["green", "red"],
                    "white",
                ),
                align="center",
            ),
        )
    )
    fig
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-08
      • 2011-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-18
      • 2013-06-26
      相关资源
      最近更新 更多