How to Create a Treemap Charts in Plotly Python?

Spread the love

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 –

  1. How to install plotly python with pip?
  2. How to create a Line Chart with Plotly Python?
  3. How to create Scatter plot in Plotly Python?
  4. How to create a Bar Chart in Plotly Python?
  5. How to create Horizontal Bar Chart in Plotly Python?
  6. How to create a Histogram in plotly python?
  7. How to Create a Box Plot in Plotly Python?
  8. How to create a Pie Chart in Plotly Python?
  9. How to create a Dot Plot in Plotly Python?
  10. How to Create Heatmap with Plotly Python?
  11. How to Create a Violin Plot in Plotly Python?
  12. How to Create Subplots in Plotly Python?
  13. How to Create a Bubble Chart in Plotly Python?
  14. How to Create a Gantt Chart in Plotly Python?
  15. How to Create an Area Chart in Plotly Python?
  16. How to Create Tables in Plotly Python?
  17. How to Create a Sunburst Chart in Plotly Python?
  18. How to Create a Sankey Diagram in Plotly Python?

Rating: 1 out of 5.

Leave a Reply