【问题标题】:How to setup a color per category accross all layers of a sunburst plotly graph in python?python - 如何在python中的旭日形图的所有层中设置每个类别的颜色?
【发布时间】:2022-01-11 16:43:51
【问题描述】:

我有一个数据框 df,如下所示:

step1    step2   step3   step4     occurances

Homepage Product Buy     Homepage 180
Homepage Product End     End      2000
Homepage End     End     End      150
Homepage Product Product Buy      100

我想创建一个旭日形图来可视化每个客户的路径。 到目前为止,这是我的代码:

fig =px.sunburst(
    df,
    path = ['step1', 'step2', 'step3', 'step4'],
    values = 'occurrances',
    color ='step2'
)
fig.show()

但是,我想在每个图层上定义每个类别的颜色,而不仅仅是图层“step2”,并在步骤 1、2、3 和 4 中为每个类别保持相同的颜色。 所以我想从这个old graph 到这个new graph 有没有人知道如何做到这一点?

提前致谢

【问题讨论】:

    标签: python plotly plotly-python sunburst-diagram


    【解决方案1】:
    import io
    import pandas as pd
    import plotly.express as px
    
    df = pd.read_csv(io.StringIO("""step1    step2   step3   step4     occurances
    Homepage Product Buy     Homepage 180
    Homepage Product End     End      2000
    Homepage End     End     End      150
    Homepage Product Product Buy      100"""), sep="\s+")
    
    fig =px.sunburst(
        df,
        path = ['step1', 'step2', 'step3', 'step4'],
        values = 'occurances',
        color ='step2'
    )
    fig.update_traces(
        marker_colors=[
            px.colors.qualitative.D3[c] for c in pd.factorize(fig.data[0].labels)[0]
        ],
        leaf_opacity=1,
    )
    

    【讨论】:

    • 非常感谢,这正是我想做的。我测试了它,它可以工作
    猜你喜欢
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    • 2011-11-16
    相关资源
    最近更新 更多