Print

81 of 100: Radar 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: I need to figure out how to add the ticks and ticklabels to all axes and remove the hardcoding of the arrows.

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
from matplotlib.lines import Line2D
from matplotlib.offsetbox import OffsetImage, AnnotationBbox

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 = { 2022: "#A54836", 2004: "#5375D4", }

xy_ticklabel_color, legend_color, grid_color, datalabels_color ='#757C85',"#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 sort the data.

 df = df.sort_values(['year', 'countries'], ascending=True ).reset_index(drop=True)
indexyearcountriessitescolor
42004Norway5#5375D4
22004Denmark4#5375D4
02004Sweden13#5375D4
52022Norway8#A54836
32022Denmark10#A54836
12022Sweden15#A54836

Define the variables

countries = df.countries.unique()
sites =  np.array(df.groupby(['year'], sort=False).sites.apply(list).tolist())
sites_radar = np.concatenate([sites,sites[:, :1]], axis = 1)
angles = np.linspace(0, 2*np.pi, len(countries), endpoint=False)
years = df.year.unique()
colors = df.color.unique()
img = [plt.imread("flags/no-rd.png"),plt.imread("flags/de-rd.png"), plt.imread("flags/sw-rd.png")]
sites22= [ l[1:4] for l in sites_radar ] #remove the first element
sites22 = [x for xs in sites22[0:] for x in xs] #flatten the list

Plot the chart

fig, ax= plt.subplots(figsize=(5,5), facecolor = "#FFFFFF",sharex=True, sharey=True, subplot_kw=dict(polar=True) )

for  site_radar,color in zip(sites_radar,colors):
    angles = np.linspace(0, 2*np.pi, len(countries), endpoint=False)
    angles = np.concatenate((angles,[angles[0]]))   
    radar_plot = ax.plot(angles, site_radar, 'o', ms= 8,mec="w",linewidth=2, color = color,zorder = 2, clip_on=False)   

ax.set_theta_zero_location('N')
ax.spines["polar"].set_color("none")
ax.set_rlim(0,20)

#add the arcs
for ang22, ang04, s22, s04,c in zip(np.tile(angles[1:4],2),np.tile(angles[0:3],2),sites22, df.sites, df.color):
    ax.annotate("", xy=(ang22,s22), xytext=(ang04,s04), zorder = 1,
                arrowprops=dict(arrowstyle='-', connectionstyle='arc3,rad=0.2', 
                          color = c,  linewidth=1, linestyle='-', antialiased=True))


#add tick labels
PAD = [[-0.2,-0.1,-0.06] ,[0.25,0.1,0.08] ,[0.1,0.05,0.03]  ]
for angle, pad in zip(angles,PAD):   
    for i,p in zip(np.arange(5,20,5),pad):
            ax.text(angle+p, i, i , size=8, color = xy_ticklabel_color )
    #add tick lines
    x=[0.4]*16
    x_left=[-0.4]*16
    for x, xl, y in zip(x,x_left,  np.arange(1,16,1)):
        rho_right = np.sqrt(x**2 + y**2)
        phi_right = np.arctan2(y, x)
        rho_left = np.sqrt(xl**2 + y**2)
        phi_left = np.arctan2(y, xl)
        ax.plot((phi_right+np.deg2rad(-90)+angle, phi_left+np.deg2rad(-90)+angle), (rho_right,rho_left),  color = xy_ticklabel_color, lw=1, zorder=0)
        ax.set_rlim(0,18)

for ang, im in zip(angles,  img):
        imagebox = OffsetImage(im, zoom=.04)
        ax.add_artist(AnnotationBbox(imagebox, (ang, 17.5), frameon = False))


#add legends
labels = [df.year.min(),df.year.max()]

lines = [Line2D([0], [0], color=c,  marker='o',linestyle='', markersize=8,) for c in colors]
plt.figlegend( lines,labels, labelcolor=legend_color,
           bbox_to_anchor=(0.5, 0.1), loc="lower center",
            ncols = 2,frameon=False, fontsize= 12)

ax.text(0,0, "▼", color = xy_ticklabel_color, ha="center", va="center")
ax.set_rticks([])
ax.set_xticklabels([])
ax.grid(False)

The result:

81 of 100: Radar 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