Last active
June 10, 2022 17:03
-
-
Save eliasdabbas/da0b5cdd6d8b99a77c3481bbb89a026f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example downloadable treemap chart: https://bit.ly/3mrz9h5
Starting with a table containing two dimensions and multiple metrics:
Run
treemap(metric, path)
to get a treemap:Interactive by default:
Select another
metric
for a different view: