Print

31 of 100: Semicircular 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: There is a bit of hardcoding here and there, need to review it.

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, grid_color, datalabels_color ='#101628', "#C8C9C9", "#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, the percentage per country as well as the pie angle and then sort the data.

df = df.sort_values([ 'year','sites', ], ascending=True ).reset_index(drop=True)
df['sub_total'] = df.groupby('year')['sites'].transform('sum')
df['pct_group'] = df['sites'] / df.sub_total
df['degrees']= df.pct_group*180
df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
#map the colors of a dict to a dataframe
df['color']= df.countries.map(color_dict)
indexyearcountriessitessub_totalpct_groupdegreesctry_codecolor
02004Denmark4220.18181832.727273DE#A54836
12004Norway5220.22727340.909091NO#2B314D
22004Sweden13220.590909106.363636SW#5375D4
32022Norway8330.24242443.636364NO#2B314D
42022Denmark10330.30303054.545455DE#A54836
52022Sweden15330.45454581.818182SW#5375D4

Define the variables

years = df.year.unique()
cod =df.ctry_code.unique()
colors =df.color.unique()

Plot the chart

fig, axes = plt.subplots(ncols =2, figsize=(8,8), sharey=True,  facecolor = "#FFFFFF", subplot_kw=dict(polar=True) )
fig.tight_layout(h_pad=-5)


radial_lim = [0.6, 1]
directions = [1,-1]
offsets = [-1,-2]
for ax,year, offset,  r_l, direction in zip(axes.ravel(),years,  offsets, radial_lim, directions):
    yr = df[df.year==year]
    countries = yr.countries.unique()
    sites = yr.sites
    codes =yr.ctry_code.unique()
    sub_total= yr.sub_total.unique()

    bottom =  np.zeros(1)
    for countries,color in zip(countries, colors): 
       # print(color)
        y = yr[yr["countries"] == countries]["degrees"].values
      
        ax.barh(range(1), np.radians(y), height= r_l,  left=bottom, color=color)
        bottom += np.radians(y)

    for bar,site,code in zip(ax.patches,sites,cod ):
        #print( code )
        x= bar.get_x() + bar.get_width()/2
        y = bar.get_height()/2 + bar.get_y()
        ax.text( x, y, f'{code}\n{site}', ha='center',va='center', color=datalabels_color,  size=12 )     

    
    ax.text(0.45,0.5, sub_total[0], size = 22, transform= ax.transAxes, color=xy_ticklabel_color, weight="bold")    
    ax.set_title(year, color=xy_ticklabel_color)    
    ax.set_theta_zero_location('N')
    ax.set_theta_direction(direction)
    ax.set_rorigin(offset)
    shift_axes = 0.2 if direction == 1 else -0.2
    box = ax.get_position()
    box.x0 = box.x0 + shift_axes #x0 first coordinate of the box
    box.x1 = box.x1 + shift_axes #x1 last coordinate of the box
    ax.set_position(box)
    ax.set_axis_off()

line = plt.Line2D((.5,.5),(0.2,0.8), color=grid_color, linewidth=1)
fig.add_artist(line)   

The result:

Stacked bar 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