Squarify
Squarify is a pure Python library that implements the squarify treemap layout algorithm. It's commonly used for data visualization, specifically to create treemaps, often in conjunction with Matplotlib. The library is currently at version 0.4.4 and appears to have an active release cadence, with the latest version released in July 2024.
Common errors
-
AttributeError: module 'squarify' has no attribute 'plot'
cause This typically occurs if a local file named `squarify.py` exists in your working directory, shadowing the installed `squarify` library. Another cause can be not importing `matplotlib.pyplot` if `squarify.plot` is being used.fixRename any local file named `squarify.py` or ensure `import matplotlib.pyplot as plt` is present if you intend to use `squarify.plot`. -
ModuleNotFoundError: No module named 'squarify'
cause The `squarify` package is not installed in the Python environment you are currently using, or there's a mismatch between where it's installed and where your interpreter is looking.fixInstall the package using `pip install squarify`. If using a virtual environment or Jupyter/IDE, ensure the correct Python interpreter path is selected. -
Labels for small treemap squares overlap or go out of bounds, making them unreadable.
cause By default, `squarify.plot` may not automatically adjust label font sizes or positions for very small rectangles, leading to visual clutter.fixManually adjust font size using `text_kwargs={'fontsize': N}` or consider adding custom logic for label placement/wrapping for smaller squares. For highly dynamic or dense treemaps, some labels may need to be omitted.
Warnings
- gotcha Input `sizes` list must be positive values and sorted in descending order before passing to `squarify.squarify` or `squarify.plot`.
- gotcha For `squarify.squarify` (the layout function), the sum of `sizes` should equal the total area (`dx * dy`). Use `squarify.normalize_sizes(values, dx, dy)` to prepare your values if they don't already match the target area.
- gotcha The `squarify` algorithm prioritizes aspect ratios close to 1. This can sometimes lead to less clarity in hierarchical structures or instability in layout with small data changes compared to other treemap algorithms.
Install
-
pip install squarify
Imports
- squarify
from squarify import squarify
import squarify
- pyplot
import matplotlib.pyplot as plt
Quickstart
import squarify
import matplotlib.pyplot as plt
sizes = [500, 433, 78, 25, 25, 7]
labels = ['Category A', 'Category B', 'Category C', 'Category D', 'Category E', 'Category F']
colors = ['#4C72B0', '#55A868', '#C44E52', '#8172B2', '#CCB974', '#64B5CD']
# Sort sizes in descending order as required by squarify
sizes.sort(reverse=True)
plt.figure(figsize=(10, 6))
squarify.plot(sizes=sizes, label=labels, color=colors, alpha=0.8)
plt.title('Treemap Visualization with Squarify')
plt.axis('off') # Removes axes to show only the treemap
plt.show()