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.

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()
namesparents
0Company
1SalesCompany
2MarketingCompany
3TechCompany
4North RegionSales

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"
)

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"
)