Q&A 43 How do you visualize hierarchical part-to-whole relationships using a treemap?
43.1 Explanation
A treemap displays hierarchical data as nested rectangles, where:
- Each rectangle’s size represents a quantitative variable (e.g., count or proportion)
- Nested levels represent grouping or hierarchy (e.g., category → subcategory)
- Color can encode an additional dimension, such as magnitude or category
Treemaps are ideal for:
- Showing relative size within a group
- Exploring distribution across hierarchical levels
- Compactly summarizing data with many categories
They offer a clearer alternative to pie charts or bar plots when visualizing complex, nested structures.
43.2 Python Code
import pandas as pd
import plotly.express as px
# Sample hierarchical data
data = pd.DataFrame({
"group": ["Setosa", "Setosa", "Versicolor", "Versicolor", "Virginica", "Virginica"],
"subgroup": ["Short", "Long", "Short", "Long", "Short", "Long"],
"value": [20, 30, 25, 25, 15, 35]
})
# Create treemap
fig = px.treemap(
data,
path=["group", "subgroup"],
values="value",
color="group",
title="Treemap of Iris Subgroups"
)
fig.show()