62 of 100: Treemap in matplotlib
At the beginning of the year I challenged myself to create all 100 visualizations using python and matplotlib from the 1 dataset,100 visualizations project and I am sharing with you the code for all the visualizations.
Note: Data Viz Project is copyright Ferdio and available under a Creative Commons Attribution – Non Commercial – No Derivatives 4.0 International license. I asked Ferdio and they told me they used a Design tool to create all the plots.
Collaborate
There are a ton of improvements that can be made on the code, so let me know in the comments any improvements you make and I will update the post accordingly!
This is the original viz that we are trying to recreate in matplotlib:

Import the packages
We will need the following packages:
import matplotlib.pyplot as plt
from matplotlib.patches import FancyBboxPatch
import pandas as pd
import squarify
Generate the data
We could actually go from numpy to matplotlib, but most data projects use pandas to transform the data, so I am using a pandas dataframe as the starting point.
data = {
"year": [2004, 2022, 2004, 2022, 2004, 2022],
"countries" : [ "Denmark", "Denmark", "Norway", "Norway","Sweden", "Sweden",],
"sites": [4,10,5,8,13,15]
}
df= pd.DataFrame(data)
index | year | countries | sites |
---|---|---|---|
0 | 2004 | Sweden | 13 |
1 | 2022 | Sweden | 15 |
2 | 2004 | Denmark | 4 |
3 | 2022 | Denmark | 10 |
4 | 2004 | Norway | 5 |
5 | 2022 | Norway | 8 |
We need to create the subtotals for each year, the country code and then sort the data.
df['sub_total'] = df.groupby('year')['sites'].transform('sum')
df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
Define the variables
years = df.year.unique()
sub_totals = df.sub_total.unique()
scalexy = [75,100]
colors = [["#CC5A43","#2C324F","#5375D4"], ["#CC5A43","#2C324F","#5375D4"]]
Plot the chart
fig, axes = plt.subplots(ncols = df.year.nunique(), nrows = 1, sharey = True, figsize=(10,5), facecolor = "#FFFFFF", zorder= 1)fig.tight_layout(pad=3.0)
for year, sub_total,color, scale, ax in zip(years, sub_totals, colors, scalexy, axes.ravel()):
sites = df[df.year ==year]['sites'].tolist()
country_code = df[df.year ==year]['ctry_code'].tolist()
ax = squarify.plot(ax = ax, sizes=sites, norm_x= scale, norm_y = scale, color = color, pad =0.2)
for rect, code, site in zip(ax.patches, country_code, sites ):
(x, y), w, h = rect.get_xy(), rect.get_width(), rect.get_height()
c = rect.get_facecolor()
#print(code, site)
#print(f'Rectangle {code} x={rect.get_x()} y={rect.get_y()} w={rect.get_width()} h={rect.get_height()} ')
ax.text(x+2,
y+h-8,
f'{code}\n{site}',
color= "w")
new_patches = []
for patch in reversed(ax.patches):
bb = patch.get_bbox()
color=patch.get_facecolor()
p_bbox = FancyBboxPatch((bb.xmin, bb.ymin),
abs(bb.width), abs(bb.height),
boxstyle="round,pad=-0.010,rounding_size=1.5",
ec="none", fc=color,
mutation_aspect=4
)
patch.remove()
new_patches.append(p_bbox)
for patch in new_patches:
ax.add_patch(patch)
ax.set_frame_on(False)
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.tick_params(axis='both', which='both',length = 0)
ax.set_xlabel(year)
ax.text(0, scale, f' Total {sub_total}')
The result:

Reader Interactions