40 of 100: Stepped 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: I want to improve how to place the flags and arrows.
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.offsetbox import OffsetImage, AnnotationBbox
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 = {"Norway": "#2B314D", "Denmark": "#A54836", "Sweden": "#5375D4", }
xy_ticklabel_color, grid_color, datalabels_color ='#101628', "#C8C9C9", "#FFFFFF"
data = {
"year": [2004, 2022, 2004, 2022, 2004, 2022],
"countries" : ["Sweden", "Sweden", "Denmark", "Denmark", "Norway", "Norway"],
"sites": [13,15,4,10,5,8]
}
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, add the sub totals, diff and color columns:
df['sub_total'] = df.groupby('year')['sites'].transform('sum')
df['diff'] = df.groupby(['countries'])['sites'].diff()
#custom sort
df = df.sort_values(by=['year', 'countries'])
#map the colors of a dict to a dataframe
df['color']= df.countries.map(color_dict)
index | year | countries | sites | sub_total | diff | color |
---|---|---|---|---|---|---|
2 | 2004 | Denmark | 4 | 22 | NaN | #A54836 |
4 | 2004 | Norway | 5 | 22 | NaN | #2B314D |
0 | 2004 | Sweden | 13 | 22 | NaN | #5375D4 |
3 | 2022 | Denmark | 10 | 33 | 6.0 | #A54836 |
5 | 2022 | Norway | 8 | 33 | 3.0 | #2B314D |
1 | 2022 | Sweden | 15 | 33 | 2.0 | #5375D4 |
Generate the colors for the tick labels
color_ticks = df[df.year==df.year.max()].sort_values("sites", ascending= False)['color'].values
color_ticks = np.insert(color_ticks, range(1,4), [["#0E0E0E"]*4,["#0E0E0E"],["#0E0E0E"]*7] )
color_ticks = np.hstack(color_ticks) #flatten the array
color_ticks
array([‘#5375D4’, ‘#0E0E0E’, ‘#0E0E0E’, ‘#0E0E0E’, ‘#0E0E0E’, ‘#A54836’, ‘#0E0E0E’, ‘#2B314D’, ‘#0E0E0E’, ‘#0E0E0E’, ‘#0E0E0E’, ‘#0E0E0E’, ‘#0E0E0E’, ‘#0E0E0E’, ‘#0E0E0E’], dtype='<U7′)
Define the variables
sites = df.sites
img = [plt.imread("flags/de-sq-transparent.png"),plt.imread("flags/no-sq-transparent.png"),plt.imread("flags/sw-sq-transparent.png"),plt.imread("flags/de-sq.png"),plt.imread("flags/no-sq.png"), plt.imread("flags/sw-sq.png")]
colors_= df.color
start_pos_arrows = df[df.year==df.year.min()]['sites'].values
end_pos_arrows = df[df.year==df.year.max()]['sites'].values
diff = df['diff'].dropna().astype(int)
text = ["bold"]+["light"]*4+["bold"]+["light"]*1+["bold"]+ ["light"]*7
Plot the chart
#create the axis
mosaic = np.zeros((15, 15), dtype=int)
for j in range(15):
mosaic[j, j] = j + 1
ax = plt.figure().subplot_mosaic(
np.fliplr(mosaic),
empty_sentinel=0,
gridspec_kw={
"wspace": 0,
"hspace": 0,
}
)
for lbl, color, text, (label,ax) in zip(reversed(range(15)), color_ticks, text, ax.items()):
ax.text(0.5, 0.5, lbl+1, ha="center", va="center", fontsize=10, color=color, weight=text)
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.tick_params(length = 0)
ax.spines[['bottom','right']].set_visible(False)
ax.spines[['top','left']].set_color(spines_color)
for site,im in zip(sites, img):
ib = OffsetImage(im, zoom=.03)
ab = AnnotationBbox(ib,
(0,0),
xybox=(site-0.6,site+0.7),
alpha=0.5,
frameon=False,
)
ax.add_artist(ab)
offset_x=0.5
offset_y=1.5
for end_pos, start_pos, color in zip(end_pos_arrows, start_pos_arrows,colors_):
ax.annotate("", xy= (start_pos-offset_x, start_pos+offset_y),
xytext=(end_pos-offset_x, end_pos+offset_y), annotation_clip= False,
arrowprops=dict(arrowstyle='-', connectionstyle='arc3,rad=0.5',
color=color, linewidth=2, linestyle='-', antialiased=True))
pos_numbers= [(7,12),(6,10), (13,17)]
for p, d, c in zip(pos_numbers, diff, colors_):
ax.annotate(f"+{str(d)}", xy= p, color= c, weight= "bold", annotation_clip=False)
The result:

Reader Interactions