Print

14 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!

To be improved: Automate the colors and the position of the arrows.

This is the original viz that we are trying to recreate in matplotlib:

Import the packages

We will use Line2D to add the legend.

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
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_label_color, legend_color, arc_color,  ='#101628',"#101628", "#757C85", 

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

Then we need to add the country codes, year labels, sub totals and sort:

df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
df['year_lbl'] ="'"+df['year'].astype(str).str[-2:].astype(str)
df['sub_total'] = df.groupby('year')['sites'].transform('sum')

sort_order_dict = {"Denmark":1, "Sweden":3, "Norway":2, 2004:4, 2022:5}
df = df.sort_values(by=['year','countries',], key=lambda x: x.map(sort_order_dict))

#map the colors of a dict to a dataframe
df['color']= df.countries.map(color_dict)
indexyearcountriessitesctry_codeyear_lblsub_totalcolor
02004Denmark4DE’0422#A54836
22004Norway5NO’0422#2B314D
42004Sweden13SW’0422#5375D4
12022Denmark10DE’2233#A54836
32022Norway8NO’2233#2B314D
52022Sweden15SW’2233#5375D4

We also need to add the color sequence for the bars, which will be site*color. I show you how I did it with numpy below, but as we are iterating over year when we create the bars, the color coding for the bars will be generated in that loop:

for year in df.year.unique():
    sites = df[df.year==year]['sites']
    colors = df[df.year==year]['color']

    bc = np.repeat(colors,sites).to_numpy() 
    print(bc)

[‘#A54836’ ‘#A54836’ ‘#A54836’ ‘#A54836’ ‘#2B314D’ ‘#2B314D’ ‘#2B314D’ ‘#2B314D’ ‘#2B314D’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’]

[‘#A54836’ ‘#A54836’ ‘#A54836’ ‘#A54836’ ‘#A54836’ ‘#A54836’ ‘#A54836’ ‘#A54836’ ‘#A54836’ ‘#A54836’ ‘#2B314D’ ‘#2B314D’ ‘#2B314D’ ‘#2B314D’ ‘#2B314D’ ‘#2B314D’ ‘#2B314D’ ‘#2B314D’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’]

Define the variables

no_bars = df.sub_total.max()
sub_totals = df.sub_total.unique()
years= df.year.unique()
color_legend= df.color
labels_legends = df.countries.unique().tolist()
arc_length = 2*np.pi/df.sub_total.min()

Plot the chart

fig, axes = plt.subplots(nrows=2, ncols=1,figsize=(6, 6), subplot_kw=dict(polar=True))
fig.tight_layout(pad=3.0)


for sub_total, year,ax in zip( sub_totals, years,axes.ravel()):
        sites = df[df.year==year]['sites']
        colors = df[df.year==year]['color']
        sites_acc = [0]+np.cumsum(sites).tolist()

        #add color list for the bars sites*color 
        bar_colors = np.repeat(colors,sites).to_numpy()
        bar_angles = 2*np.pi/sub_total

        #calculate the angles for each bar
        angles =  np.arange(0, 2*np.pi,bar_angles )
        
        ax.plot([angles, angles],[0,1],lw=4, c="#CC5A43")
        ax.set_rorigin(-4)
        ax.set_theta_zero_location("N")
        ax.set_theta_direction(-1)
        ax.set_yticklabels([])
        ax.set_xticklabels([])
        ax.grid(False)
        ax.set_rmax(1)
        ax.spines[['polar','inner']].set_color('w')
        #add year labels
        ax.text(0.5,0.5, year, size= 12, transform=ax.transAxes, ha="center", va="center", color = xy_label_color )

           #add bar colors
        for i, j in enumerate(ax.lines):
                j.set_color(bar_colors[i])

        

        # add the annotation arrows by Iterate through adjacent pairs of items in the site_Acc list
        for i, color, site  in zip(range(len(sites_acc)-1), colors, sites):
                angle_mid = np.median(np.arange(sites_acc[i]*bar_angles, sites_acc[i+1]*bar_angles , bar_angles))
                angle_range = np.arange(angle_mid-arc_length/2,angle_mid + arc_length/2, 0.001)

                r = np.ones_like(angle_range) * 1.8
                ax.plot(angle_range, r, lw=1, c=arc_color, clip_on=False)
                ax.plot([angle_mid, angle_mid], [1.8, 2.5], lw=1, c=arc_color, clip_on=False)
                ax.text(angle_mid,3.5, site, color=color, ha='center', va='center')       
   

#add legend
lines = [Line2D([0], [0], color=c, linestyle='-', lw=4,) for c in color_legend]
plt.legend(lines, labels_legends, labelcolor = legend_color,
           bbox_to_anchor=(1.7, -0.25), loc="lower center",
            frameon=False, fontsize= 10)

The result:

14 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