Skip to main content
v2026.11,986 entries · CC-BY 4.0

Treemap in Python: squarify and Plotly Express

Make a treemap in Python with squarify (flat, Matplotlib) or Plotly Express (hierarchical): install, code, reading the output and exporting for papers.

Written and maintained by CASRAI Editorial Board

Published

On this page

A treemap in Python is built with one of two libraries: squarify, which draws a flat treemap on a Matplotlib axes, or Plotly Express px.treemap, which draws a hierarchical, interactive treemap from a DataFrame. Each rectangle’s area is proportional to its value, so a treemap shows how a whole divides across many categories when a pie chart would have too many slices. If you searched for ‘treemap python’ for a manuscript figure, the short route is pip install squarify and a single call to squarify.plot() for one level of categories, or px.treemap(df, path=[...], values=...) when your categories nest inside each other.

What a treemap is used for in research

A treemap encodes a quantity as rectangle area and, in the hierarchical form, nests child rectangles inside their parent. That makes it suited to part-to-whole questions with many categories: how a set of records, samples, publications or funding awards divides across subject areas, and how each subject area divides again into subtopics. It is a poor fit when readers must compare exact values, because area is harder to judge than position along a common axis; in that case a sorted bar chart is the safer choice. For general figure-design guidance see Designing Effective Scientific Figures, and for the part-to-whole alternative with few categories see Pie Chart in Python.

The two libraries answer different needs. squarify implements the squarified treemap layout and plots it with Matplotlib, so the result is an ordinary Matplotlib figure that you can style and export like any other. It is flat: one level of categories, no nesting. Plotly Express builds the hierarchy for you from a list of columns, supports a color scale tied to the data, and produces an interactive figure in which clicking a sector zooms into it.

Install or access

Both libraries install from the Python Package Index with pip. The squarify project page on GitHub gives the command as pip install squarify, and the Plotly getting-started page gives pip install plotly. The squarify plotting function draws with Matplotlib and the examples below use pandas to hold the data, so install those too if they are not already in your environment.

pip install squarify matplotlib pandas
pip install plotly

Static image export from Plotly (PNG, PDF, SVG files) is a separate requirement. The Plotly getting-started documentation states that static export uses Kaleido, version 1.0.0 or greater, installed with pip install --upgrade kaleido, and that Kaleido needs Chrome or Chromium on the machine; if neither is present, the documentation tells you to run the plotly_get_chrome command. Interactive display and HTML export do not need Kaleido. Recording these versions in your environment file is part of computational reproducibility; see computational reproducibility.

Step-by-step: a flat treemap with squarify

  1. Import the libraries and put your categories and values in a DataFrame. The example below follows the basic treemap on the Python Graph Gallery.
import pandas as pd
import matplotlib.pyplot as plt
import squarify

df = pd.DataFrame({'nb_people': [8, 3, 4, 2],
                   'group': ['group A', 'group B', 'group C', 'group D']})
df = df.sort_values('nb_people', ascending=False)
  1. Sort the values in descending order, as above. The squarify documentation states that sizes must be positive and sorted in descending order. Sorting is also what gives the layout its large-to-small reading order.
  2. Call squarify.plot() with the sizes and the labels. The function signature is plot(sizes, norm_x=100, norm_y=100, color=None, label=None, value=None, ax=None, pad=False, bar_kwargs=None, text_kwargs=None, **kwargs) and it returns a Matplotlib Axes. Extra keyword arguments such as alpha are passed to the bars.
fig, ax = plt.subplots(figsize=(6, 4))
squarify.plot(sizes=df['nb_people'], label=df['group'], alpha=0.8, pad=True, ax=ax)
ax.axis('off')
plt.show()
  1. Turn the axes off with ax.axis('off') (the gallery example uses plt.axis('off')), because the x and y values of a treemap carry no meaning. pad=True draws a small gap between rectangles so adjacent colors stay distinguishable.
  2. Save the figure with fig.savefig('treemap.png', dpi=...), setting dpi and the file format to what your journal requires. The requirements differ by publisher; see Scientific Figure Rules for Journal Submission.

Step-by-step: a hierarchical treemap with Plotly Express

Plotly Express accepts either a tidy DataFrame with a path argument or explicit names and parents lists. The path form is the usual route for research data, because each row of the table is already a leaf and each column is a level.

import plotly.express as px

df = px.data.tips()
fig = px.treemap(df,
                 path=[px.Constant('all'), 'day', 'time', 'sex'],
                 values='total_bill')
fig.update_layout(margin=dict(t=50, l=25, r=25, b=25))
fig.show()

This is the example from the Plotly treemap documentation using the built-in tips dataset. Three details from that page matter in practice. First, path lists the columns from the root level to the leaves, and the documentation says that id and parent should not be provided when path is given. Second, for best results the first path element should be a single root node, which is what px.Constant('all') supplies. Third, if the dataset is not fully rectangular, missing values must be supplied as None.

The alternative form passes the hierarchy directly. Here names and parents are parallel lists, and a root has an empty string as its parent:

fig = px.treemap(
    names=['Eve', 'Cain', 'Seth', 'Enos', 'Noam', 'Abel', 'Awan', 'Enoch', 'Azura'],
    parents=['', 'Eve', 'Eve', 'Seth', 'Seth', 'Eve', 'Eve', 'Awan', 'Eve'])
fig.update_traces(root_color='lightgrey')
fig.show()

If you work with the lower-level graph objects instead, go.Treemap takes labels where px.treemap takes names: go.Figure(go.Treemap(labels=..., parents=..., root_color='lightgrey')). To save a standalone interactive file, fig.write_html('treemap.html') writes the figure to HTML. For a static image for a manuscript, install Kaleido as described above and call fig.write_image('treemap.png'); without Kaleido, Plotly raises an error telling you to install it.

Output and how to read it

In both libraries the area of a rectangle is proportional to its value. The Python Graph Gallery puts it directly: each square will be as big as its value. In a hierarchical Plotly treemap the area of a parent equals the sum of its children, so the parent rectangle is a visual total.

Color is a second encoding, and it behaves differently depending on the column you pass as color. The Plotly documentation states that when the color column is numeric, the color of each parent node is the value-weighted average of its children, not their sum; when the column is not numeric, a discrete color is assigned per category. A numeric example from the documentation is color='lifeExp' with color_continuous_scale='RdBu' and a color_continuous_midpoint. Because a weighted average is not a total, label the color bar with what it means, and say in the figure legend whether color is an average or a category. Figure Legends and Captions covers what a caption must contain.

In an interactive Plotly treemap you click a sector to zoom into it and use the pathbar at the upper left to zoom back out. That interaction exists only in HTML output; a static image shows one view, so choose the level that carries your message before exporting.

Troubleshooting

The rectangles look wrong or the function fails on my data

Check the sizes first. The squarify documentation requires positive values sorted in descending order. With squarify 0.4.5, a size of zero raises ZeroDivisionError, so drop zero-valued rows before plotting, or aggregate them into an ‘other’ category. Negative values cannot be shown as area at all.

I need nested categories in squarify

squarify is flat: its functions (normalize_sizes, padded_squarify, squarify and plot) lay out one list of sizes. For nested categories use Plotly Express with path, or compute the layout yourself by calling squarify.squarify(sizes, x, y, dx, dy), which returns a list of dictionaries with the keys x, y, dx and dy, once per level.

Plotly raises an error on a ragged or incomplete hierarchy

When the hierarchy is not fully rectangular, supply missing path values as None, as the Plotly documentation specifies, and keep a single root node as the first path element.

write_image fails

Static export needs Kaleido 1.0.0 or greater and Chrome or Chromium. Run pip install --upgrade kaleido, and if Chrome is missing run plotly_get_chrome, per the Plotly getting-started page.

Labels are cramped

Small rectangles cannot hold long text. In squarify, text_kwargs is passed to Matplotlib’s Axes.text, so you can reduce the font size or rotate text; bar_kwargs is passed to Axes.bar. For very small categories, fold them into an ‘other’ group or pass shorter labels.

Free alternatives and which to use

Both libraries named here are free to install from the Python Package Index. The data table below sets the parameters of squarify.plot and px.treemap side by side, with the source for each row. In short: choose squarify when you want a single-level treemap inside a Matplotlib figure you already control, and choose Plotly Express when the data nests, when color should follow a numeric variable, or when you want an interactive file as supplementary material.

Question squarify Plotly Express
Hierarchy Flat, one level Nested via path or parents
Output Matplotlib Axes Plotly figure, interactive
Input order Positive, descending No sort requirement stated; single root recommended
Color color list, passed to bars Numeric (weighted average per parent) or discrete
Static export Matplotlib savefig Kaleido 1.0.0+ and Chrome or Chromium

If you are deciding between Matplotlib-based and Plotly-based plotting in general, Plotly vs Matplotlib compares the two.

Frequently asked questions

How do I make a treemap in Python?

Install squarify and call squarify.plot(sizes=..., label=...) for a flat treemap, or install Plotly and call px.treemap(df, path=[...], values=...) for a hierarchical one. Both take area from the values you pass.

Which library should I use for a treemap in Python?

Use squarify for one level of categories in a Matplotlib figure; use Plotly Express when categories nest or when you want zoomable interactive output.

Why must squarify sizes be sorted?

The squarify documentation states that sizes must be positive and sorted in descending order; sort the DataFrame with sort_values(..., ascending=False) before plotting.

Can I save a Plotly treemap as a PNG for a paper?

Yes, with Kaleido 1.0.0 or greater installed and Chrome or Chromium available, using fig.write_image. Without Kaleido, Plotly raises an error asking you to install it.

What does color mean in a Plotly treemap?

A numeric color column colors each parent by the value-weighted average of its children; a non-numeric column gives a discrete color per category.

Sources

Data: Parameters for treemaps in Python: squarify.plot and plotly.express.treemap

A side-by-side table of the main arguments of squarify.plot and plotly.express.treemap, what each controls, and any constraint the project documentation states. Compiled from the squarify README and the Plotly treemap documentation.

Parameters for treemaps in Python: squarify.plot and plotly.express.treemap
ParameterFunctionWhat it controlsDocumented constraint or note
sizessquarify.plotValues that become rectangle areasMust be positive and sorted in descending order
labelsquarify.plotText drawn in each rectangleOptional; default None
padsquarify.plotGap between rectanglesDefault False
bar_kwargs / text_kwargssquarify.plotStyling passed to Axes.bar / Axes.textOptional; default None
pathpx.treemapColumns defining the hierarchy, root to leavesid and parent should not be provided when path is given
valuespx.treemapColumn that sets rectangle areaUsed with a path of columns
colorpx.treemapColumn that sets colorNumeric: parent is value-weighted average of children; non-numeric: discrete
names / parentspx.treemapExplicit hierarchy as parallel listsA root has an empty-string parent
labelsgo.TreemapGraph-object equivalent of namesUsed where px uses names

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Treemap in Python: squarify and Plotly Express

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →