# How to Create a Treemap Charts in Plotly Python?

In this post you will learn how to create a Treemap Charts in Plotly Python.

## Treemap Chart –

Treemap charts visualize hierarchical data using nested rectangles. Each branch of the tree is given a rectangle, which is then tiled with smaller rectangles representing sub-branches. A leaf node’s rectangle has an area proportional to a specified dimension of the data. Often the leaf nodes are colored to show a separate dimension of the data.

Let’s read a dataset to work with.

import plotly.express as px
df = px.data.gapminder().query("year == 2007")
df.head()

## Create a Treemap with px.treemap –

To create a Treemap in plotly we can use the plotly express’s px.treemap function. There are 3 things important when creating a Treemap – the path, values and the color. The path defines the structure of the treemap. The values will define the size of the rectangles in the treemap and the color is used to color the treemap. You can either use continuous color or discrete color.

Let’s create a treemap. For the path we will use this structure – first the world > continent > country. For the values we will use the population column and for the color, we will use the life Expectancy column.

fig = px.treemap(df,
path=[px.Constant("world"), 'continent', 'country'], values='pop',
color='lifeExp',
color_continuous_scale='RdBu',
color_continuous_midpoint=np.average(df['lifeExp'], weights=df['pop']))
fig.show()

### Treemap with discrete Color –

You can also use a column for the color which has discrete values. Let’s read a another dataset to show that.

df = px.data.tips()
df.head()

Now, Let’s create the treemap chart using a discrete color.

fig = px.treemap(df, path=[px.Constant("all"), 'sex', 'day', 'time'],
values='total_bill', color='day')
fig.show()

### Related Posts –

Rating: 1 out of 5.