Print

13 of 100: Radial 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

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_label_color, datalabels_color = "#101628", "#757C85"

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

Then we need to add the country codes, year labels and custom sort:

df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
df['year_lbl'] ="'"+df['year'].astype(str).str[-2:].astype(str)
sort_order_dict = {"Denmark":1, "Sweden":2, "Norway":3, }
df = df.sort_values(by=['countries',], key=lambda x: x.map(sort_order_dict))
#map the colors of a dict to a dataframe
df['color']= df.countries.map(color_dict)
indexyearcountriessitesctry_codeyear_lblcolor
02004Denmark4DE’04#A54836
12022Denmark10DE’22#A54836
42004Sweden13SW’04#5375D4
52022Sweden15SW’22#5375D4
22004Norway5NO’04#2B314D
32022Norway8NO’22#2B314D

Define the variables

countries = df.countries.unique()
sites = df.sites
years = df.year
colors = df.color

Plot the chart

fig, axes = plt.subplots(nrows=3, ncols=2,figsize=(6, 6), subplot_kw=dict(polar=True))
fig.tight_layout(pad=3.0)

for site, color, ax in zip(sites, colors, axes.ravel()):
    angles =  np.arange(0,2*np.pi,2*np.pi/site)
    ax.set_thetagrids(np.degrees(angles))
    ax.set_theta_offset(np.pi / site)
    ax.set_yticklabels([])
    ax.set_xticklabels([])
    ax.yaxis.grid(False)
    ax.xaxis.grid(linewidth=2, color= color)
    ax.spines['polar'].set_visible(False)
    ax.set_xlabel(site,  color = datalabels_color, size = 12)
   
for ax, country in zip(axes[:,0], countries):
    ax.set_ylabel(country, rotation=0,size= 12, color= xy_label_color)
    ax.yaxis.set_label_coords(-0.8, 0.5)

for ax, year in zip(axes[0], years):
    ax.set_title(year, x=0.5, y=1.2, color=xy_label_color) 

The results:

13 of 100: Radial 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