Print

35 of 100: Tabular 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

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, grand_totals_color, pie_color, datalabels_color ='#757C85',"#101628", "#ECEFEF", "#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)
indexyearcountriessites
02004Sweden13
12022Sweden15
22004Denmark4
32022Denmark10
42004Norway5
52022Norway8

We need to create the subtotals for each year so we use pandas groupby and then sort the data.

df['sub_total'] = df.groupby('year')['sites'].transform('sum')

sort_order_dict = {"Denmark":2, "Sweden":1, "Norway":3, 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)
yearcountriessitessub_totalcolor
02004Sweden1322#5375D4
22004Denmark422#A54836
42004Norway522#2B314D
12022Sweden1533#5375D4
32022Denmark1033#A54836
52022Norway833#2B314D

Define the variables

colors = df.color
countries = df.countries
years = df.year
unique_years =df.year.unique()
back_circles = [df.sites.max()]*len(df)
sites = df.sites

Plot the chart

fig, axes = plt.subplots(nrows=2, ncols=3,figsize=(10,5), facecolor = "#FFFFFF",sharex=True, sharey=True, subplot_kw=dict(polar=True) )

for  year,back_circle, site,color, ax in zip(years, back_circles,sites,colors, axes.ravel()):
    angle_range = np.linspace(0, site*25)
    angle_back_cicle = np.linspace(0, back_circle*25)
    r = np.full(len(angle_range),  6)  # identical radius values to draw an arc
    ax.plot([np.deg2rad(a) for a in angle_back_cicle],r,lw=10,color= pie_color)
    ax.plot([np.deg2rad(a) for a in angle_range],
        r,
        linewidth=10,
        solid_capstyle="round",
        color=color,)
    
    ax.annotate(xy=(np.deg2rad(0),r[-1]), xytext=(0,-60), size= 26, weight="bold", color=grand_totals_color, textcoords='offset points', text=site, ha="center",va='center')
    ax.set_rmax(7)
    ax.set_theta_zero_location('N')
    ax.set_theta_direction(-1)
    ax.grid(False)
    ax.spines['polar'].set_visible(False)
    ax.set_yticklabels([])
    ax.set_xticklabels([])

for ax, year in zip(axes[:,0], unique_years):
    ax.set_ylabel(year, rotation=0,size= 14,color=xy_ticklabel_color)
    ax.yaxis.set_label_coords(-0.5, 0.5)

for ax, col in zip(axes[0], countries):
    ax.set_title(col, x=0.5, y=1.2, color=xy_ticklabel_color) 

The result:

35 of 100: Tabular 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