Basic Interactive Treemap with Plotly

logo of a chart:Tree

This post shows how to plot a basic treemap using the plotly library in python.

The first example uses the plotly.express module and the second example uses the plotly.graph_objects module.

Plotly Express VS Plotly Graph Objects

One of the plotly particularities is that it offers two different ways to create plots: plotly.graph_objects and plotly.express. Both of them are high-level interfaces to plotly, but they have different syntaxes and functionalities. You can learn more about here.

  • Plotly express has a simpler syntax and is more user-friendly
  • Plotly graph objects, on the other side offer more flexibility and customization

In this post, we will see how to use both for treemaps. Let's start by load them (use pip install plotly if you don't have it yet):

import plotly.express as px
import plotly.graph_objects as go

# we will use pandas to read the data
import pandas as pd

# create a dataset for the treemaps
df = pd.DataFrame({
    "names": ["Company", "Sales", "Marketing", "Tech", "North Region", "South Region", "SEO", "Advertising", "Development", "Support"],
    "parents": ["", "Company", "Company", "Company", "Sales", "Sales", "Marketing", "Marketing", "Tech", "Tech"]
})
df.head()
names parents
0 Company
1 Sales Company
2 Marketing Company
3 Tech Company
4 North Region Sales

Plotly Express

fig = px.treemap(
    df,
    names='names',
    parents='parents'
)
fig.update_traces()
fig.update_layout(margin=dict(t=50, l=25, r=25, b=25))
fig.show()

Now we save it as an html element in order to render it

# save widget to html
fig.write_html(
    "../../static/interactiveCharts/580-simple-interactive-treemap-plotly-1.html"
)
%%html

<iframe
    src="../../interactiveCharts/580-simple-interactive-treemap-plotly-1.html"
    width="800"
    height="600"
    title="most simple treemap"
    style="border:none">
</iframe>

Plotly Graph Objects

fig = go.Figure(go.Treemap(
    labels=df['names'],
    parents=df['parents']
))
fig.update_layout(margin=dict(t=50, l=25, r=25, b=25))
fig.show()

Now we save it as an html element in order to render it

# save widget to html
fig.write_html(
    "../../static/interactiveCharts/580-simple-interactive-treemap-plotly-2.html"
)
%%html

<iframe
    src="../../interactiveCharts/580-simple-interactive-treemap-plotly-2.html"
    width="800"
    height="600"
    title="most simple treemap"
    style="border:none">
</iframe>

Going further

This post explains how to create treemaps with plotly, using both plotly.express and plotly.graph_objects.

You might be interested in the following posts:

Contact & Edit


👋 This document is a work by Yan Holtz. You can contribute on github, send me a feedback on twitter or subscribe to the newsletter to know when new examples are published! 🔥

This page is just a jupyter notebook, you can edit it here. Please help me making this website better 🙏!