9 of 100: Square area chart 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!
To be improved: Hardcoding on the labels, should be possible to improve.
This is the original viz that we are trying to recreate in matplotlib:

Import the packages
import matplotlib.pyplot as plt
import pandas as pd
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.
color_dict = {"Norway": "#2B314D", "Denmark": "#A54836", "Sweden": "#5375D4", }
xy_ticklabel_color, grand_totals_color, datalabels_color ='#757C85',"#101628", "#FFFFFF"
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 |
I need to add three columns to the dataframe: Subtotals, percent change and country codes as well as sort the chart.
df = df.sort_values([ 'year'], ascending=True ).reset_index(drop=True)
df['sub_total'] = df.groupby('year')['sites'].transform('sum')
df['pct_group'] = 100 * df['sites'] / df.sub_total
df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
df['color']=df.countries.map(color_dict)
index | year | countries | sites | sub_total | pct_group | ctry_code | color |
---|---|---|---|---|---|---|---|
0 | 2004 | Denmark | 4 | 22 | 18.181818 | DE | #A54836 |
1 | 2004 | Norway | 5 | 22 | 22.727273 | NO | #2B314D |
2 | 2004 | Sweden | 13 | 22 | 59.090909 | SW | #5375D4 |
3 | 2022 | Denmark | 10 | 33 | 30.303030 | DE | #A54836 |
4 | 2022 | Norway | 8 | 33 | 24.242424 | NO | #2B314D |
5 | 2022 | Sweden | 15 | 33 | 45.454545 | SW | #5375D4 |
Define the variables:
nr_years = df.year.unique()
code = df.ctry_code.unique()
pct = df.pct_group.unique()
total = df.sub_total.unique()
colors = df.color.unique()
Plot the square chart
fig, axes = plt.subplots(ncols = df.year.nunique(), nrows = 1, figsize=(10,5),sharex=True, sharey=True, facecolor = "#FFFFFF", zorder= 1)
fig.tight_layout(pad=3.0)
for yr,tot, ax in zip(nr_years,total, axes.ravel()):
temp_df = df[df.year ==yr]
y = temp_df.sub_total
w = temp_df.pct_group.tolist()
#get the new x position
xticks=[]
for n, c in enumerate(w):
xticks.append(sum(w[:n]) + w[n]/2)
ax.bar(xticks, height = y, width = w, color = colors)
ax.set_xticks([])
ax.set_yticks([])
ax.spines[['left', 'top','bottom','right']].set_visible(False)
for l1, l2, x in zip(code,pct, xticks):
ax.text(x,1, l1, color = datalabels_color, weight= "bold", ha= "center", va="center")
ax.text(x, 3, f" {int(l2)}%",size = 12, weight= "light", color = datalabels_color,ha= "center", va="center")
#add the grand totals
ax.text(50,tot+4, tot, ha="center", color = grand_totals_color, size = 30, weight= "bold")
#add the year labels
ax.set_xlabel(yr, color = xy_ticklabel_color, size = 16)
ax.xaxis.set_label_coords(0.5, -0.1)
The result:

Reader Interactions