How to Make a Treemap in Matplotlib with Squarify

Draw treemaps in Matplotlib with squarify: labels and values, color by a second measure, and a nested treemap built from rectangles.

To make a treemap in Matplotlib, install squarify and call squarify.plot(sizes=values, label=labels) with the values sorted from largest to smallest. Each rectangle's area is proportional to its value.

Install it with pip install squarify. The examples use version 0.4.5.

Quick Example

A month of household spending, with sample figures:

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

budget = pd.Series({
    "Rent": 1850, "Groceries": 620, "Transport": 410, "Savings": 540,
    "Dining out": 330, "Utilities": 260, "Health": 190, "Travel": 280,
    "Subscriptions": 75, "Gifts": 60,
}).sort_values(ascending=False)

colors = ["#264653", "#287271", "#2a9d8f", "#8ab17d", "#babb74",
          "#e9c46a", "#efb366", "#f4a261", "#ee8959", "#e76f51"]
labels = [f"{name}\n${value:,}" if value > 150 else "" for name, value in budget.items()]

fig, ax = plt.subplots(figsize=(10, 6))
squarify.plot(sizes=budget, label=labels, color=colors, norm_x=100, norm_y=60,
              bar_kwargs={"edgecolor": "white", "linewidth": 2},
              text_kwargs={"color": "white", "fontsize": 11, "fontweight": "bold"},
              ax=ax)
ax.set_title(f"Monthly spending: ${budget.sum():,}", fontsize=14, loc="left")
ax.axis("off")
fig.tight_layout()
plt.show()

Treemap of monthly spending with Rent at $1,850 taking the largest tile, followed by Groceries, Savings and Transport

Rent is $1,850 of $4,615, or 40% of the area. What to set:

  • color: without it, squarify picks random colors from the default colormap, so they change on every run.
  • norm_x and norm_y: the layout's dimensions. Match their ratio to the figure (10 x 6 here), or the tiles come out stretched.
  • Labels: squarify doesn't shrink or hide text, so blank the labels on small tiles yourself.
  • pad=True leaves gaps between tiles. A white edgecolor gives a similar look without shrinking the tiles.

Sort the Values First

squarify lays tiles out in the order given and doesn't sort them. The algorithm keeps tiles close to square only when values are in descending order.

unsorted = [60, 620, 75, 1850, 190, 540, 260, 330, 280, 410]

fig, axes = plt.subplots(1, 2, figsize=(10, 3.8))
for ax, sizes, title in zip(axes, [unsorted, sorted(unsorted, reverse=True)],
                            ["Unsorted", "Sorted, largest first"]):
    squarify.plot(sizes=sizes, color=["#adc8e6"] * len(sizes), ax=ax,
                  value=sizes, norm_x=100, norm_y=75,
                  bar_kwargs={"edgecolor": "#1d3557", "linewidth": 1},
                  text_kwargs={"fontsize": 8})
    ax.set_title(title)
    ax.axis("off")
fig.tight_layout()
plt.show()

The same values laid out unsorted, with thin slivers, and sorted, with more square tiles

Sort labels and colors along with the sizes. Keeping them in one pandas Series or DataFrame makes that automatic. All values must be positive, and a zero raises ZeroDivisionError, so filter those out.

Color a Treemap by a Second Value

Size can show one measure and color another. Map the values through a colormap with TwoSlopeNorm to center it on zero. squarify.squarify() returns the rectangle coordinates, which lets you set each label's text color separately.

from matplotlib.colors import TwoSlopeNorm

change = pd.Series({
    "Rent": 4.0, "Groceries": 9.5, "Transport": -6.0, "Savings": 12.0,
    "Dining out": -14.0, "Utilities": 2.5, "Health": 0.0, "Travel": 18.0,
    "Subscriptions": -20.0, "Gifts": -3.0,
})[budget.index]

norm = TwoSlopeNorm(vmin=-20, vcenter=0, vmax=20)
cmap = plt.get_cmap("RdBu_r")
tile_colors = cmap(norm(change.to_numpy()))
labels = [f"{n}\n{c:+.1f}%" if budget[n] > 150 else "" for n, c in change.items()]

fig, ax = plt.subplots(figsize=(10, 6))
squarify.plot(sizes=budget, color=tile_colors, norm_x=100, norm_y=60,
              bar_kwargs={"edgecolor": "white", "linewidth": 2}, ax=ax)
rects = squarify.squarify(
    squarify.normalize_sizes(budget, 100, 60), 0, 0, 100, 60)
for rect, label, value in zip(rects, labels, change):
    ax.text(rect["x"] + rect["dx"] / 2, rect["y"] + rect["dy"] / 2, label,
            ha="center", va="center", fontsize=11,
            color="white" if abs(value) > 10 else "black")
ax.axis("off")
ax.set_title("Spending by size, change from last year by color", loc="left")
fig.colorbar(plt.cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax, shrink=0.8,
             label="Change (%)")
fig.tight_layout()
plt.show()

Treemap with tile sizes for spending and a red to blue scale for change: Travel and Savings red for increases, Dining out and Subscriptions blue for decreases

Nested Treemap with Two Levels

squarify has no function for hierarchies, but you can run the layout twice: once for the groups, then once inside each group's rectangle. This uses population estimates from the public domain Natural Earth country file, read with GeoPandas.

import geopandas as gpd
from matplotlib.patches import Rectangle

world = gpd.read_file(
    "https://naciscdn.org/naturalearth/110m/cultural/ne_110m_admin_0_countries.zip")
keep = ["Africa", "Asia", "Europe", "North America", "Oceania", "South America"]
pop = world.loc[world["CONTINENT"].isin(keep), ["NAME", "CONTINENT", "POP_EST"]]
pop = pop.replace({"NAME": {"United States of America": "United States"}})

totals = pop.groupby("CONTINENT")["POP_EST"].sum().sort_values(ascending=False)
palette = dict(zip(totals.index, ["#bc4749", "#386641", "#1d3557",
                                  "#e09f3e", "#6a4c93", "#00798c"]))
W, H = 100, 62

fig, ax = plt.subplots(figsize=(11, 7))
outer = squarify.squarify(squarify.normalize_sizes(totals, W, H), 0, 0, W, H)

for box, (continent, total) in zip(outer, totals.items()):
    countries = (pop[pop["CONTINENT"] == continent]
                 .sort_values("POP_EST", ascending=False))
    sizes = squarify.normalize_sizes(countries["POP_EST"], box["dx"], box["dy"])
    inner = squarify.squarify(sizes, box["x"], box["y"], box["dx"], box["dy"])

    for r, name in zip(inner, countries["NAME"]):
        ax.add_patch(Rectangle((r["x"], r["y"]), r["dx"], r["dy"],
                               facecolor=palette[continent], edgecolor="white",
                               linewidth=0.6))
        # label only tiles wide and tall enough to hold the name
        if r["dx"] > len(name) * 0.85 and r["dy"] > 3:
            ax.text(r["x"] + r["dx"] / 2, r["y"] + r["dy"] / 2, name,
                    ha="center", va="center", color="white", fontsize=9)

    ax.add_patch(Rectangle((box["x"], box["y"]), box["dx"], box["dy"],
                           fill=False, edgecolor="white", linewidth=4))

handles = [Rectangle((0, 0), 1, 1, color=palette[c]) for c in totals.index]
ax.legend(handles, [f"{c} ({t / totals.sum():.0%})" for c, t in totals.items()],
          ncols=3, loc="upper left", bbox_to_anchor=(0, 0), frameon=False)
ax.set(xlim=(0, W), ylim=(0, H))
ax.set_title("World population by continent and country (Natural Earth estimates)",
             loc="left")
ax.axis("off")
fig.tight_layout()
plt.show()

Nested treemap of world population. Asia fills 59 percent, with China and India the two largest tiles, followed by Africa, Europe, North America, South America and Oceania

Asia holds 59% of the population in this file, and China and India together 36%.

squarify or Plotly Treemap?

Use When
squarify with Matplotlib A static chart with one level, or two with a little extra code
Plotly's px.treemap() Several levels, hover labels, and click-to-zoom
Bar chart Readers need to compare similar values precisely

Similar Topics