Visualize Hierarchical Data Beautifully with Treemaps in Python

As a data scientist, one of the most important skills to master is effective data visualization. Being able to present complex datasets in a clear, intuitive way allows you to convey insights to stakeholders and drive better decision making.

While there are many common chart types like bar graphs, line charts, and pie charts, some data structures require more specialized visualization techniques. One example is hierarchical data, which has multiple levels of categories nested within each other.

Treemaps are a powerful way to visualize hierarchical data. They display data as a series of nested rectangles, where the size of each rectangle corresponds to a quantitative value. This allows you to quickly identify patterns and compare relative magnitudes, even across multiple levels of a hierarchy.

In this article, we‘ll dive into how to create beautiful, customizable treemaps in Python using the Squarify library. Whether you‘re analyzing product categories, customer segments, geographic regions, or any other hierarchical dataset, this step-by-step guide will equip you with a valuable tool for your data visualization toolkit.

What is a Treemap?

Before we get into the technical details, let‘s make sure we understand what a treemap is and when you might use one. A treemap is a visualization that represents hierarchical data as a set of nested rectangles.

Each branch of the tree is given a rectangle, which is then tiled with smaller rectangles representing sub-branches. The size of each rectangle corresponds to a quantitative value such as revenue, population, impressions, etc. Color can also be used to represent an additional data dimension.

Here‘s a simple example treemap showing the breakdown of marketing spend across different channels and subcategories:

In this example, the size of each rectangle represents the amount of spending in that category, while the color indicates ROI (darker = higher ROI). We can immediately spot that Paid Search is the channel with the highest spend, with Google Ads being the biggest subcategory. Display is the second largest channel, and Social is the smallest.

This type of visualization makes it easy to compare both the relative spend and ROI performance across multiple levels of the hierarchy, something that would be difficult to do in a simple table or another chart type. That‘s the power of treemaps!

Some common use cases for treemaps include:

  • Sales data broken down by region, product category, salespeople, etc.
  • Web analytics showing traffic by country, referrer, device type, etc.
  • Investment portfolios with asset classes, sectors, geographies, etc.
  • Population demographics split by country, state, county, etc.

Any time you have hierarchical data with quantitative values and want to visualize the composition and allow comparisons, treemaps are a great choice.

Creating Treemaps in Python with Squarify

Now that you have a high-level understanding of treemaps, let‘s get into the specifics of how to build them in Python. We‘ll be using the Squarify library, which makes it quick and easy to create treemaps with just a few lines of code.

The first step is to install Squarify, which you can do using pip:

pip install squarify

Once installed, we can import it along with matplotlib for plotting:

import matplotlib.pyplot as plt
import squarify

The main function we‘ll be using is squarify.plot(). You pass it a list of values, and optionally labels and colors, and it will return a matplotlib plot object representing the treemap.

Here‘s a minimal example:

sizes = [100, 50, 30, 20, 10, 5] 
labels = ["Category A", "Category B", "Category C", "Category D", "Category E", "Category F"]

plt.figure(figsize=(10, 5))
squarify.plot(sizes=sizes, label=labels, color=["red","green","blue","yellow","orange","grey"], alpha=.7)
plt.title("Treemap of Categories")
plt.axis(‘off‘)
plt.show()

Let‘s break this down:

  • We specify the data as a Python list called sizes
  • The labels for each rectangle are passed as a separate list labels
  • We customize the appearance by setting explicit colors, transparency (alpha), and figure size
  • The squarify.plot() function creates the plot, which we then label and display

While this example only has one level of hierarchy, you can represent multiple levels by nesting lists. Here‘s an example showing sales broken down by sales rep and product category:

sales = {
  "North": [10, 5, 15], 
  "South": [5, 10, 5],
  "West": [15, 10, 5]
}

labels = [ ["North", "South", "West"], ["Product A", "Product B", "Product C"] ]

plt.figure(figsize=(12, 8))
squarify.plot(sizes=[val for sublist in sales.values() for val in sublist], 
              label=[f"{key} - {prod}" for key in sales.keys() for prod in labels[1]],
              color=[plt.cm.Blues(i/8) for i in range(9)],
              alpha=.8)

plt.title("Sales Treemap by Region and Product")
plt.axis(‘off‘)
plt.show()

A few things to note here:

  • We represent the hierarchical data as a nested dictionary sales, where each key is a region and the values are lists of sales by product
  • The labels now have two levels, specified as nested lists
  • We use a color map plt.cm.Blues to automatically assign shades of blue to each rectangle
  • The label text combines the region and product names to uniquely identify each rectangle

Hopefully these examples give you a sense of how flexible Squarify is. You can customize the treemap in many ways:

  • Color: Pass a list of color strings, a color map, or even a dictionary mapping labels to specific colors
  • Alpha: Set transparency of the rectangles (0 = fully transparent, 1 = fully opaque)
  • Padding: Add spacing between rectangles by setting pad=True
  • Labels: Show or hide labels, specify font size, color, etc.
  • Edgecolor: Draw borders around rectangles in a specific color
  • Figure size: Change the size/aspect ratio of the overall plot

We don‘t have space to cover every option here, but refer to the Squarify documentation for the full set of parameters you can use to fine-tune your treemaps.

Tips for Effective Treemaps

We‘ve covered the technical details of creating treemaps in Python, but what separates a good treemap from a bad one? Here are some tips to keep in mind:

  1. Keep it simple. Treemaps can quickly become cluttered and overwhelming if you try to show too many levels of hierarchy or have too many small rectangles. Generally aim for no more than 3 levels of nesting and consider grouping together tiny slices.

  2. Use color purposefully. Color is a powerful way to encode an additional data dimension, but make sure the meaning is clear. Stick to a single color scheme (e.g. shades of blue) and use a legend to explain what the colors represent. Avoid using too many disparate colors.

  3. Label strategically. Labels are essential for understanding what each rectangle represents. However, they can also add a lot of visual clutter. Consider only labeling larger rectangles and using hover interactions to show labels on smaller ones if necessary.

  4. Order thoughtfully. By default, Squarify will place the largest rectangles in the upper left and smaller ones in the lower right. For some datasets, it may make sense to override this by sorting your data in a specific way before passing it to Squarify (e.g. alphabetically, by sub-category, etc.)

  5. Facilitate comparisons. One of the key benefits of treemaps is the ability to compare relative sizes. Make sure the quantitative values you‘re encoding are actually meaningful to compare. Consider showing %‘s of the total. And beware of 3D effects or other distortions that can make comparisons harder.

  6. Tell a story. At the end of the day, your treemap should convey a clear insight to your audience. Before creating one, ask yourself what story you want to tell and how a treemap in particular will help you do that. Annotate the treemap or pair it with additional context to emphasize your main takeaways.

Limitations of Treemaps

For all their benefits, treemaps do have some limitations to be aware of:

  • They are not great at showing fine-grained differences between values that are very similar. Bar charts may be a better choice in those cases.
  • Treemaps pack rectangles tightly, which can make it hard to gauge their relative size precisely. They are best for showing broad differences.
  • The nesting of rectangles can make it tricky to compare items that are not adjacent to each other.
  • Treemaps generally don‘t show changes over time. For that, you may want a line graph, stacked area chart, or small multiples of treemaps.
  • Treemaps rely heavily on area size to encode values, so may not be the best choice for audiences who struggle interpreting area (e.g. people with visual impairments).

None of these limitations are deal-breakers, but it‘s good to keep them in mind. Make sure to choose the right visualization for the specific story you want to tell and audience you want to reach.

Conclusion

We covered a lot of ground in this article, but the key takeaways are:

  1. Treemaps are a powerful way to visualize hierarchical data. They show composition, allow comparisons, and make efficient use of space.

  2. Squarify is a Python library that makes it easy to create treemaps with just a few lines of code. It offers tons of customization options for fine-tuning your designs.

  3. When creating a treemap, keep the design simple, use color purposefully, label strategically, order thoughtfully, facilitate comparisons, and always aim to tell a clear story.

  4. Be aware of the limitations of treemaps, such as difficulty comparing similar values or showing changes over time. Choose the right chart type for your particular use case and audience.

  5. We showed several code examples, but the best way to master treemaps is to practice! Find a hierarchical dataset relevant to your work, play around with Squarify, and see what insights you can uncover.

Data visualization is a key skill for data scientists and analysts. Hopefully this guide gives you the foundation to start creating your own beautiful, insightful treemaps in Python. Happy visualizing!

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