How to Build Stunning Treemaps in Python: A Step-by-Step Guide

Introduction to Treemaps

Treemaps are a fascinating and visually appealing way to display hierarchical data. Invented in the early 1990s by Ben Shneiderman at the University of Maryland, treemaps use nested rectangles to show the relative sizes of different categories and subcategories.

The area of each rectangle is proportional to a quantitative variable, allowing you to quickly spot the biggest contributors and outliers in your data. Treemaps work especially well when you have hierarchical, "part-to-whole" data and want to understand high-level patterns rather than make precise comparisons.

For example, a sales dashboard could use a treemap to show revenue broken down by region, product category, and SKU. The biggest rectangles would immediately draw your eye to the top money-makers. You could also use treemaps to visualize website traffic, investment portfolios, election results, and much more.

Advantages of Treemaps

So what makes treemaps so useful compared to old standbys like pie and bar charts? There are a few key advantages:

1. Space efficiency: Treemaps pack a ton of data into a compact space. By nesting rectangles, you can display multiple levels of a hierarchy without the chart getting too cluttered or overwhelming. This makes treemaps great for dashboards and infographics where real estate is limited.

2. Pattern spotting: The human brain is great at visually processing relative sizes and spotting differences. Treemaps leverage this ability by encoding your data into rectangle areas. Bigger rectangles pop out immediately, drawing your attention to the most significant parts of the data. Outliers and trends are easy to identify at a glance.

3. Hierarchical data: Many real-world datasets have hierarchical relationships, such as sales data rolled up by region and product category. Treemaps preserve this hierarchical structure, whereas other chart types like bar charts lose that information. With a treemap, you can see how individual subcategories relate to the whole.

Real-World Use Cases

To make these concepts concrete, let‘s look at some real-world use cases for treemaps. One common application is visualizing product sales and customer complaints.

Imagine you work for a consumer electronics company and want to understand which products are generating the most revenue and the most customer complaints across different regions. You could use a treemap to size rectangles by sales numbers and color-code them by complaint volume.

At a glance, you would see your bestsellers as the largest rectangles. If any of those big rectangles are also colored red, it means that product has a high complaint rate relative to its sales – a problem that needs attention! You could also see which regions tend to have more complaints and warrant further investigation.

Another use case is visualizing website or app traffic. Each rectangle could represent a section of your site, sized by page views or session durations. You would quickly zero in on the most visited pages and how engagement is distributed across your site map.

Treemaps are also great for displaying financial data. You could visualize your investment portfolio, with rectangle sizes showing the dollar amount allocated to each asset class, sector, and individual holding. At a company level, you could show how resources are allocated across different business units, product lines, and geographies.

Building Treemaps in Python

Now that you‘re convinced of the power of treemaps, let‘s dive into how to build them in Python! We‘ll walk through three methods using popular data visualization libraries: Matplotlib with Squarify, Plotly Express, and Pygal.

For each example, we‘ll use a simple dataset of sales data broken down by region and product category. The full code is available on GitHub, but we‘ll explain each step here.

Method 1: Matplotlib and Squarify

Our first treemap will use the core Python data visualization library, Matplotlib, along with an add-on called Squarify to handle the treemap layout. Here‘s the code:

import pandas as pd
import matplotlib.pyplot as plt
import squarify

# Load data 
data = {‘Region‘: [‘North‘, ‘North‘, ‘South‘, ‘South‘, ‘East‘, ‘East‘, ‘West‘, ‘West‘],
        ‘Category‘: [‘A‘, ‘B‘, ‘A‘, ‘B‘, ‘A‘, ‘B‘, ‘A‘, ‘B‘], 
        ‘Sales‘: [100, 200, 150, 225, 75, 300, 200, 175]}
df = pd.DataFrame(data)

# Prepare data
grouped_data = df.groupby([‘Region‘, ‘Category‘]).sum().unstack()
sizes = grouped_data[‘Sales‘].values.flatten()
labels = [f‘{region}-{category}‘ 
          for region in grouped_data.index
          for category in grouped_data.columns]

# Plot chart
fig, ax = plt.subplots(1, figsize=(12, 8))
colors = [‘#f7fcfd‘, ‘#e0ecf4‘, ‘#bfd3e6‘, ‘#9ebcda‘, ‘#8c96c6‘, ‘#8c6bb1‘, 
          ‘#88419d‘, ‘#6e016b‘]
squarify.plot(sizes=sizes, label=labels, color=colors, alpha=0.8, ax=ax)
plt.axis(‘off‘)
plt.title("Sales by Region and Category", fontsize=18)
plt.show()

The key steps are:

  1. Load the data into a pandas DataFrame
  2. Group and sum the sales data by Region and Category using pd.groupby() and unstack()
  3. Flatten the resulting Series to get the sizes and labels for the treemap rectangles
  4. Use squarify.plot() to draw the rectangles, specifying a color palette
  5. Remove the axes and add a title

This produces a treemap like this:

Method 2: Plotly Express

For our next example, we‘ll use the powerful Plotly Express library, which supports a wide range of interactive charts. The code is even simpler:

import plotly.express as px

fig = px.treemap(df, 
                 path=[‘Region‘, ‘Category‘], 
                 values=‘Sales‘,
                 color=‘Sales‘,
                 color_continuous_scale=px.colors.sequential.Purples)

fig.update_layout(title=‘Sales by Region and Category‘)
fig.show()

Here we pass the raw DataFrame to px.treemap() and specify the hierarchy using the path parameter. We also color-code the rectangles by Sales value and choose a built-in sequential color scale.

The resulting chart is interactive – you can hover over rectangles to see the values and click to zoom in on different levels of the hierarchy:

Method 3: Pygal

Finally, let‘s build a treemap using Pygal, a lesser-known but still capable Python charting library. Pygal outputs charts as SVGs, which can be easily embedded in web pages.

import pygal

treemap = pygal.Treemap(inner_radius=0.3)
treemap.title = ‘Sales by Region and Category‘

for region in df[‘Region‘].unique():
    treemap.add(region, [{
        ‘value‘: row[‘Sales‘],
        ‘label‘: f"{row[‘Category‘]}-{row[‘Sales‘]}"
    } for _, row in df[df[‘Region‘] == region].iterrows()])

treemap.render_to_file(‘pygal-treemap.svg‘)

To build the treemap, we:

  1. Create a Treemap object with some style customization
  2. Loop through each Region and add the Category values using a list comprehension
  3. Render the result to an SVG file

The Pygal treemap has a clean, flat design aesthetic:

Tips for Effective Treemaps

Whichever tool you choose, there are some best practices to keep in mind when building treemaps:

  1. Don‘t overload the chart with too many categories. Aim for less than 10 rectangles at each level of the hierarchy. If you have more, filter the data or break it into multiple charts.

  2. Use color strategically to highlight important insights, but don‘t go overboard. Stick to a simple, muted color palette unless you really want to draw attention to outliers. Avoid red-green combinations that are hard to distinguish for colorblind users.

  3. Make your treemaps interactive if possible, so users can explore the different levels of the hierarchy. Plotly makes this easy with zooming and tooltip interactions.

  4. Experiment with different layout algorithms to find the most effective representation of your data. Squarify is a good default, but other options like slice-and-dice or strip may work better for certain datasets.

Latest Tools and Libraries

The Python data visualization ecosystem is always evolving, and there have been some exciting developments in treemaps since this article was first published in 2021.

The Bokeh library, known for its high-performance interactive visualizations, added native support for treemaps in version 2.4 (released in 2022). It leverages an efficient "squarified" treemap algorithm and supports hover tooltips, click interactions, and exporting as high-quality PNGs.

There‘s also a new entrant called Treemap.js that‘s specifically designed for visualizing large hierarchical datasets. It uses an optimized "stripify" algorithm and WebGL rendering to generate treemaps with millions of data points in real-time. While not strictly a Python library, it‘s a great option if you‘re dealing with huge datasets and need maximum performance.

Conclusion

Treemaps are a powerful way to visualize hierarchical data and uncover insights at a glance. By leveraging the human brain‘s ability to compare relative sizes and spot patterns, they can pack a ton of information into a compact, engaging chart.

Python makes it easy to build custom treemaps with a variety of libraries. Whether you choose the simplicity of Matplotlib, the interactivity of Plotly, or the style of Pygal, you can create stunning visualizations with just a few lines of code. And with new tools like Bokeh and Treemap.js pushing the boundaries of scale and performance, the possibilities are endless.

So what are you waiting for? Grab your data and start exploring the world of treemaps. You never know what insights are hiding in those rectangles, just waiting to be uncovered!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Similar Posts