Skip to content

Commit c7bf08f

Browse files
committed
treemap example with continuous colorscale
1 parent 0087ce5 commit c7bf08f

File tree

1 file changed

+81
-1
lines changed

1 file changed

+81
-1
lines changed

python/treemaps.md

+81-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ jupyter:
66
extension: .md
77
format_name: markdown
88
format_version: '1.1'
9-
jupytext_version: 1.2.1
9+
jupytext_version: 1.1.1
1010
kernelspec:
1111
display_name: Python 3
1212
language: python
@@ -149,6 +149,86 @@ fig = go.Figure(go.Treemap(
149149
fig.show()
150150
```
151151

152+
### Treemap chart with a continuous colorscale
153+
154+
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.
155+
156+
In the right subplot which has a `maxdepth` of two levels, click on a sector to see its breakdown to lower levels.
157+
158+
```python
159+
import plotly.graph_objects as go
160+
from plotly.subplots import make_subplots
161+
import pandas as pd
162+
163+
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/sales_success.csv')
164+
print(df.head())
165+
166+
levels = ['salesperson', 'county', 'region'] # levels used for the hierarchical chart
167+
color_columns = ['sales', 'calls']
168+
value_column = 'sales'
169+
170+
def build_hierarchical_dataframe(df, levels, value_column, color_columns=None):
171+
"""
172+
Build a hierarchy of levels for Sunburst or Treemap charts.
173+
174+
Levels are given starting from the bottom to the top of the hierarchy,
175+
ie the last level corresponds to the root.
176+
"""
177+
df_all_trees = pd.DataFrame(columns=['id', 'parent', 'value', 'color'])
178+
for i, level in enumerate(levels):
179+
df_tree = pd.DataFrame(columns=['id', 'parent', 'value', 'color'])
180+
dfg = df.groupby(levels[i:]).sum(numerical_only=True)
181+
dfg = dfg.reset_index()
182+
df_tree['id'] = dfg[level].copy()
183+
if i < len(levels) - 1:
184+
df_tree['parent'] = dfg[levels[i+1]].copy()
185+
else:
186+
df_tree['parent'] = 'total'
187+
df_tree['value'] = dfg[value_column]
188+
df_tree['color'] = dfg[color_columns[0]] / dfg[color_columns[1]]
189+
df_all_trees = df_all_trees.append(df_tree, ignore_index=True)
190+
total = pd.Series(dict(id='total', parent='',
191+
value=df[value_column].sum(),
192+
color=df[color_columns[0]].sum() / df[color_columns[1]].sum()))
193+
df_all_trees = df_all_trees.append(total, ignore_index=True)
194+
return df_all_trees
195+
196+
197+
df_all_trees = build_hierarchical_dataframe(df, levels, value_column, color_columns)
198+
average_score = df['sales'].sum() / df['calls'].sum()
199+
200+
fig = make_subplots(1, 2, specs=[[{"type": "domain"}, {"type": "domain"}]],)
201+
202+
fig.add_trace(go.Treemap(
203+
labels=df_all_trees['id'],
204+
parents=df_all_trees['parent'],
205+
values=df_all_trees['value'],
206+
branchvalues='total',
207+
marker=dict(
208+
colors=df_all_trees['color'],
209+
colorscale='RdBu',
210+
cmid=average_score),
211+
hovertemplate='<b>%{label} </b> <br> Sales: %{value}<br> Success rate: %{color:.2f}',
212+
name=''
213+
), 1, 1)
214+
215+
fig.add_trace(go.Treemap(
216+
labels=df_all_trees['id'],
217+
parents=df_all_trees['parent'],
218+
values=df_all_trees['value'],
219+
branchvalues='total',
220+
marker=dict(
221+
colors=df_all_trees['color'],
222+
colorscale='RdBu',
223+
cmid=average_score),
224+
hovertemplate='<b>%{label} </b> <br> Sales: %{value}<br> Success rate: %{color:.2f}',
225+
maxdepth=2
226+
), 1, 2)
227+
228+
fig.update_layout(margin=dict(t=10, b=10, r=10, l=10))
229+
fig.show()
230+
```
231+
152232
### Nested Layers in Treemap
153233

154234
The following example uses hierarchical data that includes layers and grouping. Treemap and [Sunburst](https://plot.ly/python/sunburst-charts/) charts reveal insights into the data, and the format of your hierarchical data. [maxdepth](https://plot.ly/python/reference/#treemap-maxdepth) attribute sets the number of rendered sectors from the given level.

0 commit comments

Comments
 (0)