Print

59 of 100: Linked circular scatter 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 bit of hardcoding for the arrows and missing the curved text.

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

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 ='#929EA7',"#929EA7"

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([ 'countries', 'year'], ascending=True ).reset_index(drop=True)
#map the colors of a dict to a dataframe
df['color']= df.countries.map(color_dict)
yearcountriessitescolor
02004Denmark4#A54836
12022Denmark10#A54836
22004Norway5#2B314D
32022Norway8#2B314D
42004Sweden13#5375D4
52022Sweden15#5375D4

Define the variables

countries = df.countries.unique()
years = df.year.unique()
sites =df.sites
max_sites = df.sites.max()+1
colors = df.color.unique()
edge_colors = df.color
face_colors = [["w"]*3, colors]

Plot the chart

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

for year,face_colors in zip(years,face_colors):
    temp_df = df[df.year==year]

    for site,face_color,edge_color in zip(temp_df.sites,face_colors,colors):
        ax.scatter((2 *np.pi)/ max_sites *site, 1,s=100,lw= 2,fc= face_color, ec=edge_color,zorder =1, clip_on=False)


ax.axvline( 0, 0.9, 1.1, color=grid_color, lw=1,zorder =0,clip_on= False )
ax.axvline( (2 *np.pi)/max_sites * (max_sites-1) , 0.9, 1.1, color=grid_color, lw=1,zorder =0,clip_on= False )

one_widget_angle= 360/max_sites
ax.set_theta_zero_location("N")
ax.set_theta_offset(np.deg2rad(90-one_widget_angle/2)) #rotate 0 position
ax.set(thetamin=0, thetamax=360-one_widget_angle)
thetatick_locs = np.arange(0,360,360/max_sites)
thetatick_labels = range(0,max_sites,1)

ax.set_thetagrids(thetatick_locs, thetatick_labels ,fontsize=12, zorder =0,color = "#929EA7" )

#add the polar labels
for label, angle in zip(ax.get_xticklabels(), thetatick_locs):
    x, y = label.get_position()
    lab = ax.text(x, y-0.05, label.get_text(), transform=label.get_transform(), 
                  ha=label.get_ha(), va=label.get_va(),color = xy_ticklabel_color)
    if angle <= 180:
        lab.set_rotation(0-angle)
    else:
        lab.set_rotation(360-angle)

ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_theta_direction(-1)
ax.set_rmax(1)
ax.grid(False,)
ax.spines[['start','end']].set_color('w')
ax.spines[['polar']].set_color(grid_color)

for k, spine in ax.spines.items():  #ax.spines to the back
    spine.set_zorder(0)

sites2022 = df[df.year==df.year.max()]['sites']
sites2004 = df[df.year==df.year.min()]['sites']
for s22,s04, color in zip(sites2022,sites2004,colors):
    #create the arrows
    ax.annotate("",
                    xy=((2 *np.pi)/ max_sites *s22,0.95),  # theta, radius
                    xytext=((2 *np.pi)/ max_sites *s04,0.95),
                    arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0.5',
                                color=color, linewidth=2, linestyle='-', antialiased=True))


#add legend
color_legend = ["w","#838B93"]
marker_edge_color = ["#838B93","#838B93"]
lines = [Line2D([0], [0], color=c,  marker='o',linestyle='',markeredgecolor=ec, markersize=10,) for c, ec in zip(color_legend, marker_edge_color)]
plt.figlegend( lines,years,
           bbox_to_anchor=(0.5, 0), loc="lower center",
            ncols = 2,frameon=False, fontsize= 10)

The result:

59 of 100: Linked circular scatter 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