Skip to content

Commit 0087ce5

Browse files
committed
sunburst example with continuous colorscale
1 parent 64e3bc0 commit 0087ce5

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

python/sunburst-charts.md

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,5 +155,85 @@ fig.update_layout(
155155
fig.show()
156156
```
157157

158+
### Sunburst chart with a continuous colorscale
159+
160+
The example below visualizes a breakdown of sales (corresponding to sector width) and call success rate (corresponding to sector color) by region, county and salesperson level. For example, when exploring the data you can see that although the East region is behaving poorly, the Tyler county is still above average -- however, its performance is reduced by the poor success rate of salesperson GT.
161+
162+
In the right subplot which has a `maxdepth` of two levels, click on a sector to see its breakdown to lower levels.
163+
164+
```python
165+
import plotly.graph_objects as go
166+
from plotly.subplots import make_subplots
167+
import pandas as pd
168+
169+
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/sales_success.csv')
170+
print(df.head())
171+
172+
levels = ['salesperson', 'county', 'region'] # levels used for the hierarchical chart
173+
color_columns = ['sales', 'calls']
174+
value_column = 'sales'
175+
176+
def build_hierarchical_dataframe(df, levels, value_column, color_columns=None):
177+
"""
178+
Build a hierarchy of levels for Sunburst or Treemap charts.
179+
180+
Levels are given starting from the bottom to the top of the hierarchy,
181+
ie the last level corresponds to the root.
182+
"""
183+
df_all_trees = pd.DataFrame(columns=['id', 'parent', 'value', 'color'])
184+
for i, level in enumerate(levels):
185+
df_tree = pd.DataFrame(columns=['id', 'parent', 'value', 'color'])
186+
dfg = df.groupby(levels[i:]).sum(numerical_only=True)
187+
dfg = dfg.reset_index()
188+
df_tree['id'] = dfg[level].copy()
189+
if i < len(levels) - 1:
190+
df_tree['parent'] = dfg[levels[i+1]].copy()
191+
else:
192+
df_tree['parent'] = 'total'
193+
df_tree['value'] = dfg[value_column]
194+
df_tree['color'] = dfg[color_columns[0]] / dfg[color_columns[1]]
195+
df_all_trees = df_all_trees.append(df_tree, ignore_index=True)
196+
total = pd.Series(dict(id='total', parent='',
197+
value=df[value_column].sum(),
198+
color=df[color_columns[0]].sum() / df[color_columns[1]].sum()))
199+
df_all_trees = df_all_trees.append(total, ignore_index=True)
200+
return df_all_trees
201+
202+
203+
df_all_trees = build_hierarchical_dataframe(df, levels, value_column, color_columns)
204+
average_score = df['sales'].sum() / df['calls'].sum()
205+
206+
fig = make_subplots(1, 2, specs=[[{"type": "domain"}, {"type": "domain"}]],)
207+
208+
fig.add_trace(go.Sunburst(
209+
labels=df_all_trees['id'],
210+
parents=df_all_trees['parent'],
211+
values=df_all_trees['value'],
212+
branchvalues='total',
213+
marker=dict(
214+
colors=df_all_trees['color'],
215+
colorscale='RdBu',
216+
cmid=average_score),
217+
hovertemplate='<b>%{label} </b> <br> Sales: %{value}<br> Success rate: %{color:.2f}',
218+
name=''
219+
), 1, 1)
220+
221+
fig.add_trace(go.Sunburst(
222+
labels=df_all_trees['id'],
223+
parents=df_all_trees['parent'],
224+
values=df_all_trees['value'],
225+
branchvalues='total',
226+
marker=dict(
227+
colors=df_all_trees['color'],
228+
colorscale='RdBu',
229+
cmid=average_score),
230+
hovertemplate='<b>%{label} </b> <br> Sales: %{value}<br> Success rate: %{color:.2f}',
231+
maxdepth=2
232+
), 1, 2)
233+
234+
fig.update_layout(margin=dict(t=10, b=10, r=10, l=10))
235+
fig.show()
236+
```
237+
158238
#### Reference
159239
See https://plot.ly/python/reference/#sunburst for more information and chart attribute options!

0 commit comments

Comments
 (0)