From 0087ce5617aa3fe6916639992c8dda8b63da8356 Mon Sep 17 00:00:00 2001 From: Emmanuelle Gouillart Date: Thu, 7 Nov 2019 14:36:38 -0500 Subject: [PATCH 1/3] sunburst example with continuous colorscale --- python/sunburst-charts.md | 80 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/python/sunburst-charts.md b/python/sunburst-charts.md index 9207ed7de..3f1d39981 100644 --- a/python/sunburst-charts.md +++ b/python/sunburst-charts.md @@ -155,5 +155,85 @@ fig.update_layout( fig.show() ``` +### Sunburst chart with a continuous colorscale + +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. + +In the right subplot which has a `maxdepth` of two levels, click on a sector to see its breakdown to lower levels. + +```python +import plotly.graph_objects as go +from plotly.subplots import make_subplots +import pandas as pd + +df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/sales_success.csv') +print(df.head()) + +levels = ['salesperson', 'county', 'region'] # levels used for the hierarchical chart +color_columns = ['sales', 'calls'] +value_column = 'sales' + +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(numerical_only=True) + 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) +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='%{label}
Sales: %{value}
Success rate: %{color:.2f}', + name='' + ), 1, 1) + +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='%{label}
Sales: %{value}
Success rate: %{color:.2f}', + maxdepth=2 + ), 1, 2) + +fig.update_layout(margin=dict(t=10, b=10, r=10, l=10)) +fig.show() +``` + #### Reference See https://plot.ly/python/reference/#sunburst for more information and chart attribute options! From c7bf08ffe241d4f20ababb229024e1154f1a62e9 Mon Sep 17 00:00:00 2001 From: Emmanuelle Gouillart Date: Thu, 7 Nov 2019 14:40:03 -0500 Subject: [PATCH 2/3] treemap example with continuous colorscale --- python/treemaps.md | 82 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 81 insertions(+), 1 deletion(-) diff --git a/python/treemaps.md b/python/treemaps.md index c12aabb20..b63fd1829 100644 --- a/python/treemaps.md +++ b/python/treemaps.md @@ -6,7 +6,7 @@ jupyter: extension: .md format_name: markdown format_version: '1.1' - jupytext_version: 1.2.1 + jupytext_version: 1.1.1 kernelspec: display_name: Python 3 language: python @@ -149,6 +149,86 @@ fig = go.Figure(go.Treemap( fig.show() ``` +### Treemap chart with a continuous colorscale + +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. + +In the right subplot which has a `maxdepth` of two levels, click on a sector to see its breakdown to lower levels. + +```python +import plotly.graph_objects as go +from plotly.subplots import make_subplots +import pandas as pd + +df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/sales_success.csv') +print(df.head()) + +levels = ['salesperson', 'county', 'region'] # levels used for the hierarchical chart +color_columns = ['sales', 'calls'] +value_column = 'sales' + +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(numerical_only=True) + 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) +average_score = df['sales'].sum() / df['calls'].sum() + +fig = make_subplots(1, 2, specs=[[{"type": "domain"}, {"type": "domain"}]],) + +fig.add_trace(go.Treemap( + 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='%{label}
Sales: %{value}
Success rate: %{color:.2f}', + name='' + ), 1, 1) + +fig.add_trace(go.Treemap( + 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='%{label}
Sales: %{value}
Success rate: %{color:.2f}', + maxdepth=2 + ), 1, 2) + +fig.update_layout(margin=dict(t=10, b=10, r=10, l=10)) +fig.show() +``` + ### Nested Layers in Treemap 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. From 6a9a9600c727ddc74b5772a9525d3610b1a1de56 Mon Sep 17 00:00:00 2001 From: Emmanuelle Gouillart Date: Fri, 8 Nov 2019 14:33:17 -0500 Subject: [PATCH 3/3] updated examples --- python/sunburst-charts.md | 2 +- python/treemaps.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/python/sunburst-charts.md b/python/sunburst-charts.md index 3f1d39981..d7687c728 100644 --- a/python/sunburst-charts.md +++ b/python/sunburst-charts.md @@ -171,7 +171,7 @@ print(df.head()) levels = ['salesperson', 'county', 'region'] # levels used for the hierarchical chart color_columns = ['sales', 'calls'] -value_column = 'sales' +value_column = 'calls' def build_hierarchical_dataframe(df, levels, value_column, color_columns=None): """ diff --git a/python/treemaps.md b/python/treemaps.md index b63fd1829..a0b3364f7 100644 --- a/python/treemaps.md +++ b/python/treemaps.md @@ -165,7 +165,7 @@ print(df.head()) levels = ['salesperson', 'county', 'region'] # levels used for the hierarchical chart color_columns = ['sales', 'calls'] -value_column = 'sales' +value_column = 'calls' def build_hierarchical_dataframe(df, levels, value_column, color_columns=None): """