75 of 100: Icon 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 the following packages:
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.lines import Line2D
from svgpathtools import svg2paths
from svgpath2mpl import parse_path
import numpy as np
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 = { 2022: "#A54836", 2004: "#5375D4", }
xy_ticklabel_color, legend_color, grid_color, datalabels_color ='#101628',"#101628", "#C8C9C9", "#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 |
We need to sort the data.
df['diff']=df.groupby('countries')['sites'].diff().fillna(df.sites).astype(int)
df['sub_total'] = df.groupby('countries')['diff'].transform('sum')
#custom sort
sort_order_dict = {"Denmark":2, "Sweden":1, "Norway":3, 2004:5, 2022:4}
df = df.sort_values(by=['countries','year',], key=lambda x: x.map(sort_order_dict))
#map the colors of a dict to a dataframe
df['color']= df.year.map(color_dict)
year | countries | sites | diff | sub_total | color | |
---|---|---|---|---|---|---|
5 | 2022 | Sweden | 15 | 2 | 15 | #A54836 |
4 | 2004 | Sweden | 13 | 13 | 15 | #5375D4 |
1 | 2022 | Denmark | 10 | 6 | 10 | #A54836 |
0 | 2004 | Denmark | 4 | 4 | 10 | #5375D4 |
3 | 2022 | Norway | 8 | 3 | 8 | #A54836 |
2 | 2004 | Norway | 5 | 5 | 8 | #5375D4 |
Create the heritage symbol
icon_path, attributes = svg2paths('flags/Unesco_World_Heritage_logo_notext_transparent.svg')
#matplotlib path object of the icon
icon_marker = parse_path(attributes[0]['d'])
icon_marker.vertices -= icon_marker.vertices.mean(axis=0)
icon_marker = icon_marker.transformed(mpl.transforms.Affine2D().rotate_deg(180))
icon_marker = icon_marker.transformed(mpl.transforms.Affine2D().scale(-1,1))
Define the variables
countries = df.countries.unique()
sites = df.sites
years = df.year.unique().tolist()
sub_total = df.sub_total.unique()
#create the matrix
X= np.repeat(np.arange(1,6),3)
Y = np.tile(np.arange(1,4),5)
Plot the chart
fig, axes = plt.subplots(nrows=1, ncols=3,figsize=(8,4))
for ax,country, total in zip(axes.ravel(), countries, sub_total):
#add the colors for the symbol
diff= df[df.countries==country]['diff']
colors= df[df.countries==country]['color']
symbol_color = np.insert(np.repeat(colors,diff).to_numpy(), 0, ["#FFFFFF"]*(15-total))
ax.scatter(Y,X, marker=icon_marker, s=800, color= symbol_color)
ax.set_xlim(0,4)
ax.set_ylim(0,6)
ax.invert_xaxis()
ax.set_title(country, weight= "bold", color= xy_ticklabel_color)
ax.axis('off')
#add legend
text_legends = ["Before", "After"]
lines = [Line2D([0], [0], color=c, marker=icon_marker,linestyle='', markersize=20,) for c in colors]
labels = [f'{text_legend} 2004' for year, text_legend in zip(years, text_legends)]
for year in years:
plt.figlegend( lines,labels,
labelcolor=legend_color,
bbox_to_anchor=(0.5, -0.05), loc="lower center",
ncols = 2,frameon=False, fontsize= 12)
The result:

Reader Interactions