Print

28 of 100: Nested half circles 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: A lot of hardcoding of the positions and labels, need to review.

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.patches import Wedge
from matplotlib.lines import Line2D
from matplotlib.markers import MarkerStyle
import pandas as pd
import numpy as np

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, grid_color, datalabels_color ='#757C85',"#101628", "#C8C9C9", "#FFFFFF"

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 percentage change and then sort the data.

df['sub_total'] = df.groupby('countries')['sites'].transform('sum')
df['pct_change'] = df.groupby('countries', sort=False)['sites'].apply(
     lambda x: x.pct_change()).to_numpy()*-1
df = df.sort_values(['year','sites' ], ascending=True ).reset_index(drop=True)
#map the colors of a dict to a dataframe
df['color']= df.countries.map(color_dict)
indexyearcountriessitessub_totalpct_changecolor
02004Denmark414NaN#A54836
12004Norway513NaN#2B314D
22004Sweden1328NaN#5375D4
32022Norway813-0.600000#2B314D
42022Denmark1014-1.500000#A54836
52022Sweden1528-0.153846#5375D4

Define the variables

sites =df.sites.to_numpy()
colors = df.color
theta1, theta2 = 0, 180

radius = (sites/2)
radius[3:] *= -1

centers = [(sites[i]/2,0) for i in range(6)]

label_x = df.groupby(['year','sites'])['sites'].agg(sum).to_list()

label_y = np.repeat([0.2, 0.4],len(df.countries.unique()))
label_y[3:] *= -1

Plot the chart

fig, ax = plt.subplots( figsize=(10,5), facecolor = "#FFFFFF")
ax.set_aspect('equal')

for radie, lb_y,lb_x, site, color, center in zip(radius, label_y, label_x, df.sites, reversed(colors), centers):
    patches = Wedge(center, radie, theta1, theta2, color=color,)
    ax.add_patch(patches)
    ax.annotate(lb_x, xy=(lb_x-0.6, lb_y ),  fontsize=8, color = "w",) 

ax.text(-4, 1, df.year.min(), color=xy_ticklabel_color, size=12 )
ax.text(-4, -2, df.year.max(), color=xy_ticklabel_color, size=12 )

ax.axhline(y=0,xmin=-4,xmax=17, color =grid_color,lw=0.5,snap=False)
ax.set_xlim([-4, 17])
ax.set_ylim([-8, 8])

#add legend
lines = [Line2D([0], [0], color=c,  marker=MarkerStyle('o', fillstyle='top'), mec="w", linestyle='', markersize=20,) for c in colors]
labels = df.countries.unique().tolist()
plt.legend(lines, labels, labelcolor= xy_ticklabel_color,
           bbox_to_anchor=(0.5, -0.3), loc="lower center",
            ncols = 3,frameon=False, fontsize= 10)

ax.set_xticklabels([])
ax.set_yticklabels([])       
ax.set_frame_on(False)
ax.tick_params(axis='both', which='both',length = 0)

The result:

28 of 100: Nested half circles 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