24 of 100: Stacked progress bar 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: To be able to add the country flags at the data labels level, I added blank images for the lower chart. I am sure this can be improved. Need to remove the hardcoding of colors and other stuff. Will revisit later.
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 matplotlib.patheffects as pe
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, flag_text_color, grid_color, datalabels_color ='#101628',"#101628", "#E3E6E8", "#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 create the subtotals for each year, the percentage total, add country codes and sort the data.
df['pct_tot']= df['sites'] / df.groupby('year')['sites'].transform('sum')
df['sub_total'] = df.groupby('countries')['sites'].transform('sum')
df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
df = df.sort_values([ 'countries','year'], ascending = True).reset_index(drop=True)
sort_order_dict = {"Denmark":1, "Sweden":3, "Norway":2, 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.countries.map(color_dict)
index | year | countries | sites | pct_tot | sub_total | ctry_code | color |
---|---|---|---|---|---|---|---|
1 | 2022 | Denmark | 10 | 0.303030 | 14 | DE | #A54836 |
0 | 2004 | Denmark | 4 | 0.181818 | 14 | DE | #A54836 |
3 | 2022 | Norway | 8 | 0.242424 | 13 | NO | #2B314D |
2 | 2004 | Norway | 5 | 0.227273 | 13 | NO | #2B314D |
5 | 2022 | Sweden | 15 | 0.454545 | 28 | SW | #5375D4 |
4 | 2004 | Sweden | 13 | 0.590909 | 28 | SW | #5375D4 |
Define the variables
countries = df.countries.unique()
years = df.year.unique()
codes = df.ctry_code.unique()
#blank_image= np.array([[[255, 255, 255, 255]]], dtype='uint8')
img = [plt.imread("flags/de-rd.png"),plt.imread("flags/no-rd.png"), plt.imread("flags/sw-rd.png"),]*3
#get first and last color
color_end_bars =df.color[:1].to_list() + df.color[-1:].to_list()
color_bars = df.color.unique()
x= len(years)
Plot the chart
fig, ax = plt.subplots(figsize=(10,4), facecolor = "#FFFFFF")
#add the end of the
ax.scatter(np.array([0,1]*2),np.sort([0,1]*2), marker="o",s=1650, color = color_end_bars*2, zorder=2)
#add the stacked bars
bottom = np.zeros(x)
for ctry, col in zip(countries, color_bars):
y = df[df.countries==ctry].sort_values("countries", ascending = True)["pct_tot"].values
ax.barh(range(x), y, left=bottom, height = 0.42, zorder=1, color = col)
bottom +=y
#add the line around the bars
y=[[0,0],[1,1]]
for y in y:
ax.plot([0,1], y, linestyle='-', lw = 50, color = "w", path_effects=[pe.Stroke(linewidth=52, foreground=grid_color), pe.Normal()], solid_capstyle="round",zorder=0 )
#add data labels
for bar,pct in zip(ax.patches, df.pct_tot):
xbar= bar.get_x() + bar.get_width() /2
ybar= bar.get_height()/2 + bar.get_y()
ax.text( xbar, ybar,
f'{pct:.0%}',
ha='center',va="center", color=datalabels_color, size=16 )
#add flags only on one axis
for bar,im,code in zip(ax.patches[1::2], img, codes):
xbar= bar.get_x() + bar.get_width() /2
ybar= bar.get_height()/2 + bar.get_y()
image_box = OffsetImage(im, zoom = 0.06) #container for the image
ab = AnnotationBbox(image_box, (xbar, ybar+0.8), frameon = False)
ax.text( xbar, ybar+0.45,code, size= 12, ha= "center",color=flag_text_color)
ax.add_artist(ab)
#add straight line
y =[0,1]
for y in y:
ax.axhline(y, -1,0.5, zorder=-1 ,color= grid_color)
ax.tick_params(axis='y', which='major',length=0, labelsize=14,colors= xy_ticklabel_color)
#add years
ax.yaxis.set_ticks(range(x), labels =years)
ax.set_xlim([-0.11,1.1])
ax.set_ylim(-0.4, 1.8)
ax.spines[['left','right', 'top', 'bottom']].set_visible(False)
ax.set_xticks([])
The result:

Reader Interactions