Print

26 of 100: Semicircular 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: I need to automate it a bit more.

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.offsetbox import OffsetImage, AnnotationBbox
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 = {(2022,"Norway"): "#9194A3", (2004,"Norway"): "#2B314D",
              (2022,"Denmark"): "#E2AFA5", (2004,"Denmark"): "#A54836",
              (2022,"Sweden"): "#C4D6F8", (2004,"Sweden"): "#5375D4",
              }

xlabel_color, title_color,  datalabels_color ="#101628","#969CA3",  "#2B314D"

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 create the year labels and then sort the data.

df['year_lbl'] ="'"+df['year'].astype(str).str[-2:].astype(str)
sort_order_dict = {"Denmark":2, "Sweden":3, "Norway":1, }
df = df.sort_values(by=['countries',], key=lambda x: x.map(sort_order_dict))
#Add the color based on the color dictionary
df['color'] = df.set_index(['year', 'countries']).index.map(color_dict.get)
df['diff'] = df.groupby(['countries'])['sites'].diff()
df['diff']= np.where(df['diff'].isnull(), df.sites, df['diff']).astype(int)
yearcountriessitesyear_lblcolordiff
42004Norway5’04#2B314D5
52022Norway8’22#9194A33
22004Denmark4’04#A548364
32022Denmark10’22#E2AFA56
02004Sweden13’04#5375D413
12022Sweden15’22#C4D6F82

Define the variables

countries = df.countries.unique()
years = df.year.unique()
directions = [-1,1,-1]
codes = df.year_lbl.unique()

positions = [["left"]*2 , ["right"]*2 ,  ["left"]*2]
ctry_positions = [["right"], ["left"], ["right"]]
x_label_positions = [[0.4], [0.7], [0.4]]
x_site_positions = [[0.2], [0.6], [0.2]]
img = [plt.imread("flags/no-rd.png"),plt.imread("flags/de-rd.png"), plt.imread("flags/sw-rd.png")]

#create a list of list for coloring the radial grid lines
grid_colors = [['#E1E5E7']*g + ['w']*g for g in df.sites[1::2]]

#create the list of colors for the site label (list of lists of colors)
site_label_colors = [[i] for i in df.color[0::2].to_list()]

Plot the chart

fig, axes = plt.subplots(nrows=3, ncols=1,figsize=(5,7), facecolor = "#FFFFFF",subplot_kw=dict(polar=True),)
fig.tight_layout(pad=-4.8)


for ax, xpos , xsitepos, site_colors, country, line_color, ctry_position, position, direction, im in zip(axes.ravel(),x_label_positions, x_site_positions, site_label_colors, countries,grid_colors,ctry_positions, positions, directions,img):
    
    #add flag
    image_box =  OffsetImage(im, zoom = 0.04) #container for the image
    ab = AnnotationBbox(image_box, (0, 0), frameon = False)
    ax.add_artist(ab)

    #plit the radial lines
    sites_max = df[df.countries==country]['sites'].max()
    r= [sites_max]*(sites_max*2)
    angles =  np.arange(0,2*np.pi,2*np.pi/(sites_max*2) )
    ax.plot([angles, angles],[0,sites_max],'-',lw=1, zorder =0)

    #change the color of the radial grid lines
    for i, j in enumerate(ax.lines):
        j.set_color(line_color[i])

    #plot the bubbles
    diff = df[df.countries == country]['diff'].to_numpy()
    color = df[df.countries == country]['color'].to_numpy()
    bubble_color = [color[0]]*diff[0] +[color[1]]*diff[1] + ['w']*sites_max
    ax.scatter(angles, r,s=80,c=bubble_color,ec="w",zorder =1)

    for x, xs, site_color, pos in zip(xpos , xsitepos, site_colors, ctry_position):
        #add site label
        ax.text (xs, 0.5, f'{sites_max} ', transform = ax.transAxes, size=11, weight ="bold",color = site_color, ha= pos, va="center",)
        #add country label
        ax.text (x, 0.5, f'{country}', transform = ax.transAxes,  color= title_color, ha= pos, va="center")

    
    site = df[df.countries==country]['sites']
    for s,pos,xy_color, code in zip(site,position, color, codes):
        ax.text( angles[s-1], r[s-1], f'  {code}  ', color =xy_color,  ha = pos, va = "top", zorder =1000)

    ax.set_theta_zero_location("N") 
    ax.set_theta_direction(direction) 
    ax.set_axis_off() 
    ax.set_ylim(0,sites_max+1)

The result:

26 of 100: Semicircular 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