plotly / plotly.py

The interactive graphing library for Python :sparkles: This project now includes Plotly Express!
https://plotly.com/python/
MIT License
16.12k stars 2.54k forks source link

Multiple same layers or children not showing in sunburst #2285

Closed tayyabvohra closed 3 months ago

tayyabvohra commented 4 years ago

I am trying to show all the same childrens in the in the sunburst but it is not showing , its showing me only on one parent

this is the reference material i am using

I want to show all the male and female in the first layer but i am getting only once inside one parent

https://plot.ly/python/sunburst-charts/

this is the code

def build_hierarchical_dataframe(df, levels, value_column, color_columns=None):
    """
    Build a hierarchy of levels for Sunburst or Treemap charts.

    Levels are given starting from the bottom to the top of the hierarchy,
    ie the last level corresponds to the root.
    """
    df_all_trees = pd.DataFrame(columns=['id', 'parent', 'value', 'color'])
    for i, level in enumerate(levels):
        df_tree = pd.DataFrame(columns=['id', 'parent', 'value', 'color'])
        dfg = df.groupby(levels[i:]).sum()
        dfg = dfg.reset_index()
        df_tree['id'] = dfg[level].copy()
        if i < len(levels) - 1:
            df_tree['parent'] = dfg[levels[i+1]].copy()
        else:
            df_tree['parent'] = 'total'
        df_tree['value'] = dfg[value_column]
        df_tree['color'] = dfg[color_columns[0]] / dfg[color_columns[1]]
        df_all_trees = df_all_trees.append(df_tree, ignore_index=True)
    total = pd.Series(dict(id='total', parent='',
                              value=df[value_column].sum(),
                              color=df[color_columns[0]].sum() / df[color_columns[1]].sum()))
    df_all_trees = df_all_trees.append(total, ignore_index=True)
    return df_all_trees

df_all_trees = build_hierarchical_dataframe(df, levels, value_column, color_columns)

df_all_trees

average_score = df['sales'].sum() / df['calls'].sum()

fig = make_subplots(1, 2, specs=[[{"type": "domain"}, {"type": "domain"}]],)

fig.add_trace(go.Sunburst(
    labels=df_all_trees['id'],
    parents=df_all_trees['parent'],
    values=df_all_trees['value'],
    branchvalues='total',
    marker=dict(
        colors=df_all_trees['color'],
        colorscale='RdBu',
        cmid=average_score),
    hovertemplate='<b>%{label} </b> <br> Sales: %{value}<br> Success rate: %{color:.2f}',
    name=''
    ), 1, 2)

this is the dataframe id parent value color Female Brewster 33 0.424242424 Female Dallam 49 0.265306122 Female Hartley 42 0.880952381 Female Pecos 48 0.9375 Female Rusk 24 0.333333333 Female Shelby 29 0.206896552 Male Brewster 33 0.606060606 Male Dallam 35 0.657142857 Male Hartley 39 0.948717949 Male Pecos 30 0.833333333 Male Rusk 20 0.4 Male Shelby 45 0.355555556 Brewster West 66 0.515151515 Dallam North 84 0.428571429 Hartley North 81 0.913580247 Pecos West 78 0.897435897 Rusk East 44 0.363636364 Shelby East 74 0.297297297 East total 118 0.322033898 North total 165 0.666666667 West total 144 0.722222222 total 427 0.590163934

this is the output i am getting

newplot (1)

nicolaskruchten commented 4 years ago

Yes, the problem here is that each id must be unique and have a unique parent. Here you have the id "Female" showing up multiple times with different parents. I would recommend making your id the full path with some delimiter, so "Brewster-Female" and then using labels to get the text displaying the way you want it to.

tayyabvohra commented 4 years ago

@nicolaskruchten did you have any solution to this problem?

nicolaskruchten commented 4 years ago

Yes, as I said above:

I would recommend making your id the full path with some delimiter, so "Brewster-Female" and then using labels to get the text displaying the way you want it to.

You could also use the path argument to px.sunburst which will take care of most of this for you.

johangodinho14 commented 2 years ago

@nicolaskruchten I ran into the same issue, and looked everywhere on the internet for a solution. Finall found this thread, thanks a lot for your contribution :)

MahmoodabadiHamid commented 1 year ago

Hey guys! I ran into the same problem, and I found this thread. Look at this example:

import plotly.graph_objects as go
data = [['Market Sentiment', 'First industry', 303] ,
        ['First industry', 'Negative', 153] ,
        ['First industry', 'Neutral', 0] ,
        ['First industry', 'Positive', 150] ,

        ['Market Sentiment', 'Second  industry', 252] ,
        ['Second  industry', 'Negative', 162] ,
        ['Second  industry', 'Neutral', 0] ,
        ['Second  industry', 'Positive', 90] ,

        ['Market Sentiment', 'Third industry', 249] ,
        ['Third industry', 'Negative', 183] ,
        ['Third industry', 'Neutral', 0] ,
        ['Third industry', 'Positive', 66]]
fig =go.Figure(go.Sunburst(
    ids=[item[1] if item[0]==data[0][0] else item[0]+" "+item[1] for item in data],
    labels=[item[1] for item in data],
    parents=[item[0] for item in data],
    values=[item[2] for item in data],
    branchvalues="total",
    ))
fig.show()
skexp commented 1 year ago

Yes, as I said above:

I would recommend making your id the full path with some delimiter, so "Brewster-Female" and then using labels to get the text displaying the way you want it to.

You could also use the path argument to px.sunburst which will take care of most of this for you.

Yes, the problem here is that each id must be unique and have a unique parent. Here you have the id "Female" showing up multiple times with different parents. I would recommend making your id the full path with some delimiter, so "Brewster-Female" and then using labels to get the text displaying the way you want it to.

I tried using a number range based on the length of my label list for generating ids. But it does not yield any output. Does that mean ids must have a string that is similar to label and parent?

gvwilson commented 3 months ago

Hi - we are trying to tidy up the stale issues and PRs in Plotly's public repositories so that we can focus on things that are still important to our community. Since this one has been sitting for a while, I'm going to close it; if it is still a concern, please add a comment letting us know what recent version of our software you've checked it with so that I can reopen it and add it to our backlog. Alternatively, if it's a request for tech support, please post in our community forum. Thank you - @gvwilson