57 of 100: Donut 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 numpy as np
import pandas as pd
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
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.
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 add some fake columns to complete the pies:
df['diff'] = df.groupby(['countries'])['sites'].diff()
df['diff'].fillna(df.sites, inplace=True)
df2 = pd.DataFrame({'year':[0]*3, 'countries': ['Denmark', 'Norway','Sweden'], 'diff':[5,7,0 ]})
df3=pd.concat((df, df2)).reset_index(drop=True)
index | year | countries | sites | diff |
---|---|---|---|---|
0 | 2004 | Sweden | 13.0 | 13.0 |
1 | 2022 | Sweden | 15.0 | 2.0 |
2 | 2004 | Denmark | 4.0 | 4.0 |
3 | 2022 | Denmark | 10.0 | 6.0 |
4 | 2004 | Norway | 5.0 | 5.0 |
5 | 2022 | Norway | 8.0 | 3.0 |
6 | 0 | Denmark | NaN | 5.0 |
7 | 0 | Norway | NaN | 7.0 |
8 | 0 | Sweden | NaN | 0.0 |
Now we add the subtotals, colors and a new site columns with blanks, as well as sort the dataframe:
df3['sub_total'] = df3.groupby('countries')['diff'].transform('sum')
df3['pct_group'] = df3['diff'] / df3.sub_total
df3['degrees']= df3.pct_group*360
#custom sort
sort_order_dict = {"Denmark":2, "Sweden":1, "Norway":3, 2004:4, 2022:5, 0:6}
df3 = df3.sort_values(by=['countries','year',], key=lambda x: x.map(sort_order_dict))
df3['colors']= ["#5475D6","#AFCBFD","#ECEFEF","#CC5A43","#E2AFA5","#ECEFEF","#2B314D","#9194A3","#ECEFEF",]
df3 = df3.fillna('')
df3['sites']=df3['sites'].astype(str).str.split('.').str[0]
index | year | countries | sites | diff | sub_total | pct_group | degrees | colors |
---|---|---|---|---|---|---|---|---|
0 | 2004 | Sweden | 13 | 13.0 | 15.0 | 0.866667 | 312.0 | #5475D6 |
1 | 2022 | Sweden | 15 | 2.0 | 15.0 | 0.133333 | 48.0 | #AFCBFD |
8 | 0 | Sweden | 0.0 | 15.0 | 0.000000 | 0.0 | #ECEFEF | |
2 | 2004 | Denmark | 4 | 4.0 | 15.0 | 0.266667 | 96.0 | #CC5A43 |
3 | 2022 | Denmark | 10 | 6.0 | 15.0 | 0.400000 | 144.0 | #E2AFA5 |
6 | 0 | Denmark | 5.0 | 15.0 | 0.333333 | 120.0 | #ECEFEF | |
4 | 2004 | Norway | 5 | 5.0 | 15.0 | 0.333333 | 120.0 | #2B314D |
5 | 2022 | Norway | 8 | 3.0 | 15.0 | 0.200000 | 72.0 | #9194A3 |
7 | 0 | Norway | 7.0 | 15.0 | 0.466667 | 168.0 | #ECEFEF |
Define the variables
years = df3.year.unique()
countries = df3.countries.unique()
line_colors = [["#AFCBFD","#5475D6","#ECEFEF"],["#CC5A43","#E2AFA5","#ECEFEF"],["#2B314D","#9194A3","#ECEFEF",]]
img = [plt.imread("flags/sw-rd.png"),plt.imread("flags/de-rd.png"), plt.imread("flags/no-rd.png")]
Plot the chart
fig, axes = plt.subplots(ncols =3, figsize=(10,5), sharex=True, sharey=True, facecolor = "#FFFFFF", subplot_kw=dict(polar=True) )
fig.tight_layout(pad=3.0)
for ax,country,im in zip(axes.ravel(),countries, img ):
yr = df3[df3.countries==country]
years = yr.year.unique()
sites = yr.sites
colors = yr.colors
image_box = OffsetImage(im, zoom = 0.04) #container for the image
ab = AnnotationBbox(image_box, (0, -4), frameon = False)
ax.add_artist(ab)
bottom = np.zeros(1)
for year, in zip(years):
y = yr[yr["year"] == year]["degrees"].values
color = yr[yr["year"] == year]["colors"].values
bar = ax.barh(range(1), np.radians(y), left=bottom, color=color)
bottom += np.radians(y)
ax.set_title(country)
offset= [1.5,1.5,0]*3
for bar,site, color, offset in zip(ax.patches,sites, colors, offset):
x= bar.get_x() + bar.get_width()
y = bar.get_height()/2 + bar.get_y()
ax.text( x, y+offset, site, ha='center', color='k', size=8 )
ax.axvline( x, y, y+offset, color=color, lw=1,clip_on= False )
ax.set_theta_zero_location('N')
ax.set_theta_direction(-1)
ax.set_rorigin(-4)
ax.set_axis_off()
The result:

Reader Interactions