Print

94 of 100: Multi-level 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: I wanted to do the background as wedges, but it took too long time to figure it out, so it has been made manually for now.

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 matplotlib as mpl
import numpy as np
import pandas as pd
from svgpathtools import svg2paths
from svgpath2mpl import parse_path

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" : [ "Denmark", "Denmark", "Norway", "Norway","Sweden", "Sweden",],
    "sites": [4,10,5,8,13,15]
}
df= pd.DataFrame(data)
indexyearcountriessites
02004Sweden13
12022Sweden15
22004Denmark4
32022Denmark10
42004Norway5
52022Norway8

We need to create the subtotals for each year, the year labels and then sort the data. I also added a dummy row, for the first empty wedge of the pie. Ideally, this could have been done by splitting the pie. Will look into it later.

df['year_lbl'] ="'"+df['year'].astype(str).str[-2:].astype(str)
df['sub_total'] = df.groupby('year')['sites'].transform('sum')
df.loc[6] = [2004, "Dummy", 2, "", 22] 
df.loc[7] = [2022, "Dummy", 2, "", 33] 
df = df.sort_values(['year','sites' ], ascending=True ).reset_index(drop=True)
indexyearcountriessitesyear_lblsub_total
02004Dummy222
12004Denmark4’0422
22004Norway5’0422
32004Sweden13’0422
42022Dummy233
52022Norway8’2233
62022Denmark10’2233
72022Sweden15’2233

Create the heritage symbol

icon_path, attributes = svg2paths('flags/Unesco_World_Heritage_logo_notext_transparent.svg')
#matplotlib path object of the icon
icon_marker  = parse_path(attributes[0]['d'])

icon_marker.vertices -= icon_marker.vertices.mean(axis=0)
icon_marker = icon_marker.transformed(mpl.transforms.Affine2D().rotate_deg(180))
icon_marker = icon_marker.transformed(mpl.transforms.Affine2D().scale(-1,1))

Define the variables

sub_totals= df.sub_total.unique()
years= df.year.unique()
colors = [["w"]*1 + ["#2C324F"]*5 + ["#CC5A43"]*4 + ["#5375D4"]*13,          ["w"]*1+ ["#2C324F"]*8 + ["#CC5A43"]*10 + ["#5375D4"]*15]

#variables for the bar axis
yposition = [0.31,0.215]
height = [0.4,0.6]
radius_end = [.7,.5]

Plot the chart

fig, ax = plt.subplots(figsize=(6, 6))
fig.tight_layout(pad=3.0)

for  color,  re, sub_total,ypos,h in zip( colors,  radius_end,sub_totals,yposition, height):
        ax_pie = fig.add_axes([0.22,ypos,0.6,h], polar=True)
        angles =  np.arange(0,2*np.pi,2*np.pi/sub_total)
        ax_pie.plot([angles, angles],[0,re],lw=4,zorder = 0 )
        ax_pie.set_rorigin(-2)
        ax_pie.set_theta_zero_location("N")
        ax_pie.set_theta_direction(-1)
        ax_pie.set_axis_off()  
        for i, j in enumerate(ax_pie.lines):
                j.set_color(color[i])

#add the wedges
ax_pie.axvline( -0.12, -1.75, 1.25, color="#D3D9DB", lw=1,clip_on= False )
ax_pie.axvline( 0.12, -1.75, 1.25, color="#D3D9DB", lw=1,clip_on= False )
ax_pie.axvline( 1.62, -1.9, 1.1, color="#D3D9DB", lw=1,clip_on= False )
ax_pie.axvline( 2.72, -1.75, -0.3, color="#D3D9DB", lw=1,clip_on= False )
ax_pie.axvline( 3.53, -0.25, 1.2, color="#D3D9DB", lw=1,clip_on= False )

#add the circles
outer_circle = plt.Circle((0, 0), ec= "#D3D9DB",color= "w",radius=0.043 )
ax.add_artist(outer_circle)
mid_circle = plt.Circle((0, 0), ec= "#D3D9DB",color= "w",radius=0.03 )
ax.add_artist(mid_circle)
inner_circle = plt.Circle((0, 0), ec= "#D3D9DB",color= "w",radius=0.017 )
ax.add_artist(inner_circle)
ax.set_axis_off() 

#add the heritage symbol
ax.scatter(0,0,s=4000,  marker=icon_marker, color = "#D3D9DB") 

#add year labels
ax_pie.text(-0.1,-0.6,"'04", size = 10, color = "#848490", zorder = 2)
ax_pie.text(-0.06,0.2,"'22", size = 10, color = "#848490", zorder = 2)

The result:

94 of 100: Multi-level 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