plotly Treemap in Python (3 Examples)
Hi! This tutorial will show you how to build a plotly treemap in the Python programming language.
Treemaps are a type of data visualization that display hierarchical data using nested rectangles. In treemaps, a rectangular area is divided into smaller rectangles, each representing a different category or subcategory of the data being visualized.
First, though, here is an overview:
Let’s jump into the Python code!
Install & Import plotly & NumPy
If you do not have plotly and NumPy already installed and imported in your Python programming environment, then run the lines of code below in your preferred Python IDE to install and import both libraries; otherwise, you may skip to the next section of this tutorial:
# install plotly & NumPy pip install plotly numpy # import plotly & NumPy import plotly.express as px import numpy as np
With plotly and NumPy installed and imported into our Python coding environment, we can now access their functions for this tutorial.
Create Sample Dataset
We will make use of the popular gapminder dataset, which comes preloaded in plotly. Run the line of code below to load the dataset:
df = px.data.gapminder()
You can take a look at the first 5 rows of the dataset by running:
print(df.head(5)) # country continent year lifeExp pop gdpPercap iso_alpha iso_num #0 Afghanistan Asia 1952 28.801 8425333 779.445314 AFG 4 #1 Afghanistan Asia 1957 30.332 9240934 820.853030 AFG 4 #2 Afghanistan Asia 1962 31.997 10267083 853.100710 AFG 4 #3 Afghanistan Asia 1967 34.020 11537966 836.197138 AFG 4 #4 Afghanistan Asia 1972 36.088 13079460 739.981106 AFG 4
Next, we will filter the data for year 2002, as that is the year we are interested in:
df = px.data.gapminder().query("year == 2002") print(df.head(5)) # take a look at the first 5 rows # country continent year lifeExp pop gdpPercap iso_alpha iso_num #10 Afghanistan Asia 2002 42.129 25268405 726.734055 AFG 4 #22 Albania Europe 2002 75.651 3508512 4604.211737 ALB 8 #34 Algeria Africa 2002 70.994 31287142 5288.040382 DZA 12 #46 Angola Africa 2002 41.003 10866106 2773.287312 AGO 24 #58 Argentina Americas 2002 74.340 38331121 8797.640716 ARG 32
With the sample dataset created, we can now build the treemap.
Example 1: Create Treemap with Continuous Color Scale
In this first example, we will create a treemap with a continuous color scale to indicate different life expectancies:
fig = px.treemap(df, path = [px.Constant("world"),"continent","country"], values = "pop", color = "lifeExp", hover_data = ["iso_alpha"], color_continuous_scale = "RdBu", color_continuous_midpoint = np.average(df["lifeExp"],weights = df["pop"])) fig.update_layout(margin = dict(t = 50,l = 25, r = 25, b = 25)) fig.show()
In the above example, we created a treemap with a continuous color scale, where we parsed “RdBu” to the continuous_color_scale =
argument in the px.treemap() function. There are many other color scales from which you can choose.
We also specified the path, where we defined the root node in the hierarchy as “world”, followed by “continent” and “country”.
We then made use of NumPy’s np.average() function to compute the weighted average of life expectancy, which is displayed in the treemap on hover. The NumPy function was parsed to the color_continuous_midpoint =
argument.
Example 2: Create Treemap with Discrete Colors
In this second example, we will build the same treemap, but with a discrete color to indicate different continents:
fig = px.treemap(df, path = [px.Constant("world"),"continent","country"], values = "pop", color = "continent", hover_data = ["iso_alpha"], color_continuous_midpoint = np.average(df["lifeExp"],weights = df["pop"])) fig.update_layout(margin = dict(t = 50,l = 25, r = 25, b = 25)) fig.show()
In the example above, we parsed “continent” to the color =
argument inside the px.treemap()
function, which made each continent distinct on the map with unique colors.
In the update_layout() function, we parsed a dictionary to the margin =
argument, where we defined the top, bottom, left, and right margins.
Example 3: Create Treemap with Discrete Color Mapping
In this final example, we will build a treemap with discrete color mapping for continents:
fig = px.treemap(df, path = [px.Constant("world"),"continent", "country"], values = "pop", color = "continent", color_discrete_map={"(?)":"lightblue", "Asia":"purple", "Africa":"darkblue", "Americas":"red","Europe":"yellow","Oceania":"brown"}, hover_data = ["iso_alpha"], color_continuous_midpoint = np.average(df["lifeExp"],weights = df["pop"])) fig.update_layout(margin = dict(t = 50,l = 25, r = 25, b = 25)) fig.show()
In the example above, we created a dictionary, wherein we defined colors for the root node, symbolized by (?)
, and the individual continents, and parsed that dictionary to the color_discrete_map =
argument. Apart from that, the code is exactly the same as in the previous example.
There are many more customizations that can be done to treemaps in Python. This is just to get you started with treemaps. You can play around with the parameters, and also visualize other datasets as treemaps.
Video, Further Resources & Summary
Do you need more explanations on how to build plotly treemap in Python? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.
In the video, we explain in some more detail how to build plotly treemap in Python.
The YouTube video will be added soon.
With that, we have demonstrated how to build a plotly treemap in the Python programming language. As you can see, it is another nice way to interactively visualize hierarchical data in Python.
- plotly Sunburst Chart in Python (4 Examples)
- plotly Heatmap in Python (3 Examples)
- plotly Filled Area Plot in Python (5 Examples)
- Learn Python Programming
- Change Size of plotly Graph in Python (Example)
- Create Multiple Graphs as plotly Subplots in Python (3 Examples)
This post has shown how to build plotly treemap in Python. In case you have further questions, you may leave a comment below.
This page was created in collaboration with Ifeanyi Idiaye. You might check out Ifeanyi’s personal author page to read more about his academic background and the other articles he has written for the Statistics Globe website.
Statistics Globe Newsletter