Skip to content

Instantly share code, notes, and snippets.

@silgon
Last active January 27, 2022 22:57
Show Gist options
  • Save silgon/3cd75093bf372d42ea9f8183d60fbf7b to your computer and use it in GitHub Desktop.
Save silgon/3cd75093bf372d42ea9f8183d60fbf7b to your computer and use it in GitHub Desktop.
import plotly.express as px
df = px.data.tips()
color_map = dict(Sun="#881122", Sat="#991188", Fri="#221122", Thur="#887722")
fig = px.sunburst(df, path=['day', 'time', 'sex'], color="day", values='total_bill',
color_discrete_map=color_map)
fig.show()
## No Express (without order)
def build_hierarchical_dataframe(df, levels, value_column, color_column, color_map):
levels_rev = levels[::-1]
df_all_trees = pd.DataFrame(columns=['id', "label", 'parent', 'value', 'color'])
for i, level in enumerate(levels_rev):
df_tree = pd.DataFrame(columns=['id', "label", 'parent', 'value', 'color'])
dfg = df.groupby(levels_rev[i:]).sum()
dfg = dfg.reset_index()
df_tree['id'] = dfg[levels_rev[i:][::-1]].T.apply(lambda x: "/".join(x))
df_tree["label"] = dfg[level].copy()
if i < len(levels_rev) - 1:
df_tree['parent'] = dfg[levels_rev[i+1:][::-1]].T.apply(lambda x: "/".join(x))
else:
df_tree['parent'] = ''
df_tree['value'] = dfg[value_column]
df_tree['color'] = dfg[levels_rev[-1]].map(color_map)
df_all_trees = df_all_trees.append(df_tree, ignore_index=True)
total = pd.Series(dict(id='', parent='',
value=df[value_column].sum(),
color=""
))
df_all_trees = df_all_trees.append(total, ignore_index=True)
return df_all_trees
df = px.data.tips()
color_map = dict(Sun="#881122", Sat="#991188", Fri="#221122", Thur="#887722")
levels = ['day', 'time', 'sex']
color_column = 'day'
value_column = 'total_bill'
df_all_trees = build_hierarchical_dataframe(df, levels, value_column, color_columns, color_map)
fig = go.Figure(
go.Sunburst(
ids=df_all_trees["id"],
labels=df_all_trees["label"],
parents=df_all_trees["parent"],
values=df_all_trees["value"],
branchvalues="total",
marker=dict(colors=df_all_trees["color"]),
sort=False
)
)
fig.show()
@silgon
Copy link
Author

silgon commented Jan 27, 2022

First with express:
image
Second without express and no order:
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment