Search code examples
pythonplotlyplotly-pythonsunburst-diagram

How to setup a color per category accross all layers of a sunburst plotly graph in python?


I have a dataframe df like below:

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

I would like to create a sunburst to visualise the path of each customer. So far, this is my code :

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

However, I would like to define the colors per categories across each layer and not only layer 'step2' and keep the same color for each category in step 1, 2,3 and 4. So I would like to go from this old graph to this new graph Does anyone have an idea on how to do that?

Thanks in advance


Solution

  • 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,
    )
    

    enter image description here