Print

80 of 100: Circular 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.

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


df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
df['colors'] =["#2C324F","#2C324F","#CC5A43","#CC5A43","#5375D4","#5375D4",]

#custom sort
sort_order_dict = {"Denmark":2, "Sweden":1, "Norway":3, 2004:4, 2022:5}
df = df.sort_values(by=['countries','year',], key=lambda x: x.map(sort_order_dict))
indexyearcountriessitesctry_codecolors
42004Sweden13SW#5375D4
52022Sweden15SW#5375D4
02004Denmark4DE#2C324F
12022Denmark10DE#2C324F
22004Norway5NO#CC5A43
32022Norway8NO#CC5A43

Define the variables

codes = df.ctry_code.unique()
years = df.year.unique()

Plot the chart

fig, axes = plt.subplots(ncols = len(df.year.unique()), nrows = len(df.countries.unique()),sharex= False, figsize=(15, 15), subplot_kw=dict(polar=True))
fig.tight_layout(h_pad=-20)

shift_axes= [+0.1, -0.1]*3
for sites, shift_axes, color ,ax  in zip(df.sites, shift_axes, reversed(df.colors),axes.ravel()):
    for site in range(sites):
        angles = np.linspace(0,np.pi, 100)
        radius= np.ones(100)*site
        ax.plot(angles, radius, color=color, linestyle='-',lw=2)
        ax.set_rgrids(range(0,15))
        ax.grid(False)
        ax.spines['polar'].set_visible(False)
        ax.spines[['start','end']].set_color('#C8CCCF')
        ax.xaxis.set_label_coords(1.05, 0.19)
        ax.set_xlabel(site)
        ax.set_yticklabels([])
        ax.set_xticklabels([])
        ax.set_thetamax(180)
        ax.set_xlabel(sites, size=20)
    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.patch.set_alpha(0.1) #transparent axis
    
   
for ax, code in zip(axes[:,0], codes):
    ax.set_ylabel(code, rotation=0,size= 20,)
    ax.yaxis.set_label_coords(-0.1,0.22)
   

for ax, col in zip(axes[0], years):
    ax.set_title(col, x=0.5, y=-1.5, size = 20) 

The result:

80 of 100: Circular 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