Print

82 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: This viz is missing the curved labels.

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
from matplotlib.textpath import TextPath
from matplotlib.patches import PathPatch
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.

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 country codes and then custom sort the data.

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

Define the variables

countries = df.countries.unique()
sites = list(df.sites)
years = df.year
widths = [0,0.4]
distances =[0.8,0.65]


colors = ["#2B314D","#5375D4","#A54836",]

Plot the chart

countries = df.countries.unique()
sites = list(df.sites)
years = df.year
widths = [0,0.4]
distances =[0.8,0.65]


colors = ["#2B314D","#5375D4","#A54836",]

fig, ax = plt.subplots(figsize=(5,5), facecolor = "#FFFFFF")

for year, site,distance, width in zip(years,sites,distances,widths):
    temp_df= df[df.year ==year]
 
    ax.pie(temp_df.sites, 
            radius= 1-width,
            labels = temp_df.sites,
            labeldistance=distance,
            startangle = 90,
            pctdistance=distance,
            wedgeprops=dict(width=0.35),
            textprops=dict(color ="white",fontsize= 10),    
           colors= colors)
    
#curved text 
scale=0.005
size = 0.2
radius = 0.5 * 2 * np.pi / 2.8
text = [ "Norway", "Denmark", "Sweden",]
color_text = ["#2B314D","#A54836","#5375D4",]
angle = [-10.2  , -5.7, -7.9 ]

for text, color, angle in zip(text, color_text, angle):
    path = TextPath((0, 0), text, size=14)
    path.vertices.flags.writeable = True
    V = path.vertices
    xmin, xmax = V[:, 0].min(), V[:, 0].max()
    ymin, ymax = V[:, 1].min(), V[:, 1].max()
    V -= (xmin + xmax) / 2, (ymin + ymax) / 2
    V *= scale * np.sign(np.sin(angle) + 1e-100)
    a = angle - V[:, 0]
    V[:, 0] = (radius + V[:, 1]) * np.cos(a)
    V[:, 1] = (radius + V[:, 1]) * np.sin(a)
    patch = PathPatch(path, facecolor=color, linewidth=0)
    ax.add_artist(patch)

The result:

82 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