Skip to content

Instantly share code, notes, and snippets.

@eliasdabbas
Last active June 10, 2022 17:03
Show Gist options
  • Save eliasdabbas/da0b5cdd6d8b99a77c3481bbb89a026f to your computer and use it in GitHub Desktop.
Save eliasdabbas/da0b5cdd6d8b99a77c3481bbb89a026f to your computer and use it in GitHub Desktop.
import plotly.express as px
def treemap(traffic_df, metric='Users', path=['Medium', 'Source']):
"""Make in interactive treemap for two data dimensions/levels.
Parameters:
-----------
traffic_df : A DataFrame containing two dimensions, and one or more metrics
metric : The selected metric which you want to analyze
path : The names of the two dimensions that make the levels of the tree map (order is important)
Returns:
--------
A plotly Figure object that can be further edited
"""
fig = px.treemap(traffic_df, path=[px.Constant(metric)] + path, template='none', values=metric, height=700)
template = '<b>%{label}</b><br><br>Total: %{value:,d}<br>%{percentParent:.1%} of %{parent}<br>%{percentRoot:.1%} of %{root}'
fig.data[0]['texttemplate'] = template
fig.data[0]['hovertemplate'] = template
return fig
@eliasdabbas
Copy link
Author

eliasdabbas commented Jun 8, 2022

Example downloadable treemap chart: https://bit.ly/3mrz9h5

Starting with a table containing two dimensions and multiple metrics:

Screen Shot 2022-06-08 at 7 45 52 PM

Run treemap(metric, path) to get a treemap:

Screen Shot 2022-06-08 at 7 46 49 PM

Interactive by default:

Screen Shot 2022-06-08 at 7 46 25 PM

Select another metric for a different view:

Screen Shot 2022-06-08 at 7 46 09 PM

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