Print

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)
indexyearcountriessites
02004Sweden13
12022Sweden15
22004Denmark4
32022Denmark10
42004Norway5
52022Norway8

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)
indexyearcountriessitesdiff
02004Sweden13.013.0
12022Sweden15.02.0
22004Denmark4.04.0
32022Denmark10.06.0
42004Norway5.05.0
52022Norway8.03.0
60DenmarkNaN5.0
70NorwayNaN7.0
80SwedenNaN0.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]
indexyearcountriessitesdiffsub_totalpct_groupdegreescolors
02004Sweden1313.015.00.866667312.0#5475D6
12022Sweden152.015.00.13333348.0#AFCBFD
80Sweden0.015.00.0000000.0#ECEFEF
22004Denmark44.015.00.26666796.0#CC5A43
32022Denmark106.015.00.400000144.0#E2AFA5
60Denmark5.015.00.333333120.0#ECEFEF
42004Norway55.015.00.333333120.0#2B314D
52022Norway83.015.00.20000072.0#9194A3
70Norway7.015.00.466667168.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:

57 of 100: Donut chart in matplotlib
Was this helpful?

Reader Interactions

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents