11 of 100: Proportional 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!
This is the original viz that we are trying to recreate in matplotlib:

Import the packages
We will need matplotlib, and pandas.
We will use matplotlib.patches to create the squares.
import matplotlib.pyplot as plt
import matplotlib.patches as patches
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_label_color, datalabels_color ='#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 |
Then we need to add the country codes, year labels and colors:
df = df.sort_values([ 'year'], ascending=False ).reset_index(drop=True)
df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
df['year_lbl'] ="'"+df['year'].astype(str).str[-2:].astype(str)
#map the colors of a dict to a dataframe
df['color']= df.countries.map(color_dict)
#To ensure that the areas are really proportional, use the square root values as the length and height of the rectangles.
df['sq_sites'] = (df['sites'])**.5
year | countries | sites | ctry_code | year_lbl | color | sq_sites | |
---|---|---|---|---|---|---|---|
0 | 2022 | Denmark | 10 | DE | ’22 | #A54836 | 3.162278 |
1 | 2022 | Norway | 8 | NO | ’22 | #2B314D | 2.828427 |
2 | 2022 | Sweden | 15 | SW | ’22 | #5375D4 | 3.872983 |
3 | 2004 | Denmark | 4 | DE | ’04 | #A54836 | 2.000000 |
4 | 2004 | Norway | 5 | NO | ’04 | #2B314D | 2.236068 |
5 | 2004 | Sweden | 13 | SW | ’04 | #5375D4 | 3.605551 |
Plot the Proportional chart:
fig, axes = plt.subplots(ncols=3, nrows=1, figsize=(13,6), sharex=True, sharey=True, facecolor= "white")
fig.tight_layout(pad=2.0)
countries = df.countries.unique()
offset_axes = [0.5,0]
for country, ax in zip(countries, axes.ravel()):
sq_sites = df[df.countries==country]["sq_sites"].to_numpy()
sites = df[df.countries==country]["sites"].to_numpy()
colors = df[df.countries==country]["color"].to_numpy()
for n, (sq_site,site, offset_axis, color), in enumerate(zip(sq_sites, sites,offset_axes, colors)):
square = patches.Rectangle((offset_axis, offset_axis), sq_site, sq_site, ec="w", facecolor=color) #(x,y), width, height
ax.add_patch(square)
ax.set_xlim(-0.5, sq_sites[0]+1)
ax.set_ylim(-0.5, sq_sites[0]+1)
ax.set_xlabel(country, size=14 ,color = xy_label_color )
ax.set_aspect('equal', anchor= 'S')
ax.annotate(site, xy=(sq_site + offset_axis -0.3, sq_site + offset_axis-0.2),
fontsize=15, color = datalabels_color, ha = "center", va="top") #add the offset to the data labels
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.xaxis.set_label_coords(0.5,-0.1)
ax.set_frame_on(False)
ax.tick_params(axis='both', which='both',length = 0)
The result:

To ensure that the areas are really proportional, use the square root values as the length and height of the rectangles.
Quick fix:
df[‘sites’] = (df[‘sites’])**.5
Really appreciate all your works
Makes sense! Will change that 🙂