Treemap Basics with Python. A very straightforward way to display... | by Thiago Carvalho | Towards Data Science

There’s no shortage of visualizations to display how single values compose a whole. Some can be very complicated and specific; others like the one we’ll explore today are quite simple and easy to use.
From pies to waffles charts, the idea of showing the proportions of a whole is often an excellent beginning for storytelling. You can start with composition and then explore the distinct values individually, or compare different structures from different entities or different periods.
The visualization was first used in the 1990s by Ben Shneiderman, an American computer scientist and professor at the University of Maryland.
His visualization became very popular, and you can find different implementations and different algorithms for creating them in many tools and languages such as Tableau, PowerBi, Python, R, and much more.
For the next examples, we’ll use Python with Matplotlib, Squarify, and Pandas to create and design our treemaps. Later we’ll get a quick look at what Plotly can do.
import matplotlib.pyplot as pltimport squarify # pip install squarifyimport pandas as pd
There’s nothing complicated about Squarify, we can simply pass a list of numbers to it, and it’ll figure out the layout.
sizes = [50, 25, 12, 6]squarify.plot(sizes)plt.show()
Piece of cake.
Now, you can’t get too much information from just looking at this random squares. Maybe you can have some insights about the overall composition, but you wouldn’t be able to identify those squares unless you’re familiar with the data itself.
Let’s get more specific and add some labels to our treemap. We can also remove the axis and soften the colours a bit.
sizes=[50, 25, 12, 6]label=["50", "25", "12", "6"]squarify.plot(sizes=sizes, label=label, alpha=0.6 )plt.axis('off')plt.show()
Cool! Did you notice how the colours changed? We reduced the alpha, and that’s why their not so bright, but not only that, they also changed places.
There’s some randomness in the way colours are assigned to the squares — don’t ask me why.
Even though randomness can be useful and lead to some happy accidents, it won’t always get you a colour scheme that makes sense. To avoid that, we can define our list of colours.
sizes=[50, 25, 12, 6]label=["50", "25", "12", "6"]color=['red','blue','green','grey']squarify.plot(sizes=sizes, label=label, color=color, alpha=0.6 )plt.axis('off')plt.show()
Defining our colours to get a clearer picture is just one aspect of it.
Colours can add another encoding, for example, if we had a company in different locations we might want to see how much each of them contributes to our total assets, that would be the size of the squares in our treemap.
Then we could colormap those locations by profit, production quantities, costs, or whatever we want.
Let’s make a more accessible example just to illustrate the idea, let’s say we have four companies in two locations. We can use distinct colours for different areas, and similar colours for the ones in the same place.
sizes=[50, 25, 12, 6]label=["BC 1", "OT 1", "OT 2", "OT 3"]color=['red','#1C9FB0','#32A0CE','#1C51B0']squarify.plot(sizes=sizes, label=label, color=color, alpha=0.6 )plt.axis('off')plt.show()
Now we can have an idea of how much each one contributes, and we can also easily distinguish BC from OT.
We can use Pandas data frames instead of lists, which opens a wide array of operations we can perform in our data and add a lot to scalability.
Let’s see how well this visualization can scale. I’ll use the UK’s farm animal population by breed dataset.
df = pd.read_csv('data/animal-population-by-breed-on_1-march-2010.csv')# convert to numeric and drop nadf['Number of Animals'] = pd.to_numeric(df['Number of Animals'], errors='coerce')df.dropna(inplace=True)df.head()
Now we can pass the ‘Number of Animals’ as our size and the ‘Breed’ as our labels.
fig, ax = plt.subplots(1, figsize = (12,12))squarify.plot(sizes=df['Number of Animals'],               label=df['Breed'],               alpha=.8 )plt.axis('off')plt.show()
Uh, that’s not good. Too many labels!
Let’s try sorting our data frame and labelling just the largest squares.
df.sort_values('Number of Animals', ascending=False, inplace=True)df
fig, ax = plt.subplots(1, figsize = (12,12))squarify.plot(sizes=df['Number of Animals'],               label=df['Breed'][:5],               alpha=.8 )plt.axis('off')plt.show()
Awesome! With sorted data and labels just for the most significant populations, we can get some insights.
With Plotly, we can go even further with our treemaps, grouping data, adding tooltips, and colormaps are extremely simple.
Let’s go through a quick example, just to illustrate the possibilities. I’ll use a Video Game Sales dataset and Plotly Express.
First, let’s load the data and remove the empty rows.
df = pd.read_csv('data/vgsales.csv')df.dropna(inplace=True)df
Now let’s plot it! We’ll pass the data frame, the path to the fields containing the categories, the sizes of the squares, and the intensity of the colours.
Plotly will draw our plot with a colormap, add a colour bar, tooltips, and resize the labels according to the size of the squares.
import plotly.express as pxfig = px.treemap(df,                  path=['Platform', 'Genre'],                  values='Global_Sales',                 color='NA_Sales'                )fig.show()
Ok, the labels are not readable for every square, but we do have tooltips to help us figure out the ones we can’t read, and we added a lot more information here than in the previous ones.
I’m personally not a big fan of interactivity; honestly, it’s hard for me to figure out how to add it to the story — I mean, we began exploring treemaps as a starter for storytelling and as a way to simplify the composition, but this visualization is not so friendly.
With interactivity and complexity added to our visualization, I would suggest the opposite. Start with the specific insights you found by showing individual squares, or groups, and then at the end, present your full treemap to allow the user to explore it by itself.
Take a look at Nadieh Bremer’s storytelling with Chord Diagrams. Her final visualization is quite complicated. Still, the way she goes through the details before showing you the big picture is fantastic and makes the data much more understandable.
Here’s a link for the interactive viz we created, and here you can find the code.
Thanks for reading my article. I hope you enjoyed it.
Resources:Treemaps University of Maryland;Python Graph Gallery — Treemap;Datacadamia — Treemaps;Plotly — Treemaps;Plotly — HTML export;Github — Squarify;