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
- 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)
- 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.
- Call
squarify.plot()with the sizes and the labels. The function signature isplot(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 asalphaare 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()
- Turn the axes off with
ax.axis('off')(the gallery example usesplt.axis('off')), because the x and y values of a treemap carry no meaning.pad=Truedraws a small gap between rectangles so adjacent colors stay distinguishable. - Save the figure with
fig.savefig('treemap.png', dpi=...), settingdpiand 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
- Plotly, Treemap Charts in Python, https://plotly.com/python/treemaps/ (read 2026-11-14).
- Plotly, Getting Started with Plotly in Python, https://plotly.com/python/getting-started/ (read 2026-11-14).
- laserson, squarify (GitHub), https://github.com/laserson/squarify (read 2026-11-14).
- The Python Graph Gallery, Basic treemap with Python, https://python-graph-gallery.com/200-basic-treemap-with-python/ (read 2026-11-14).
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.
| Parameter | Function | What it controls | Documented constraint or note |
|---|---|---|---|
| sizes | squarify.plot | Values that become rectangle areas | Must be positive and sorted in descending order |
| label | squarify.plot | Text drawn in each rectangle | Optional; default None |
| pad | squarify.plot | Gap between rectangles | Default False |
| bar_kwargs / text_kwargs | squarify.plot | Styling passed to Axes.bar / Axes.text | Optional; default None |
| path | px.treemap | Columns defining the hierarchy, root to leaves | id and parent should not be provided when path is given |
| values | px.treemap | Column that sets rectangle area | Used with a path of columns |
| color | px.treemap | Column that sets color | Numeric: parent is value-weighted average of children; non-numeric: discrete |
| names / parents | px.treemap | Explicit hierarchy as parallel lists | A root has an empty-string parent |
| labels | go.Treemap | Graph-object equivalent of names | Used where px uses names |
Sources
- squarify (GitHub README) (accessed 2026-11-14)
- Plotly: Treemap Charts in Python (accessed 2026-11-14)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







