Print

93 of 100: Donut 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!

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",
              }

xy_ticklabel_color, xlabel_color,  grid_color,  ='#9BA0A6',"#9BA0A6", "#E9ECED", 


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 difference between the number of sites by year, the subtotals, the percentage and then sort the data.

df = df.sort_values([ 'year'], ascending=True ).reset_index(drop=True)
df['diff'] = df.groupby(['countries'])['sites'].diff()
df['diff'].fillna(df.sites, inplace=True)
df['sub_total'] = df.groupby('countries')['diff'].transform('sum')
df['pct_group'] = (df['diff'] / df.sub_total)*100
df['pct_group'] = df['pct_group'].astype(int)
#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))

#Add the color based on the color dictionary
df['color'] = df.set_index(['year', 'countries']).index.map(color_dict.get)
indexyearcountriessitesdiffsub_totalpct_groupcolor
02004Sweden1313.015.086#5375D4
32022Sweden152.015.013#C4D6F8
12004Denmark44.010.040#A54836
42022Denmark106.010.060#E2AFA5
22004Norway55.08.062#2B314D
52022Norway83.08.037#9194A3

Define the variables

x_img = df[df.year == df.year.min()]["sites"].values
y_img = df[df.year == df.year.max()]["sites"].values

x_pie = [0.767,0.165,0.233]
y_pie = [0.9,0.565,0.435]
color = df.color
countries = df.countries.unique()

img = [plt.imread("flags/sw-rd.png"),plt.imread("flags/de-rd.png"), plt.imread("flags/no-rd.png")]

Plot the chart

fig, ax = plt.subplots(figsize=(5,5), facecolor = "#FFFFFF", zorder= 1)

for country, xa,ya in zip(countries, x_pie,y_pie):
    sites = df[df.countries==country]['diff']
    pct = df[df.countries==country]['pct_group']
    color = df[df.countries==country]['color']

    ax_pie = ax.inset_axes([xa,ya,0.2,0.2])
    wedges, texts = ax_pie.pie(sites,wedgeprops=dict(width=0.5),  labels= pct, labeldistance=1.2,textprops={'fontsize': 10 },
         counterclock=False,startangle=90, colors = color)
    for text, color in zip(texts, color):
        text.set_color(color)


for im,x,y in zip(img,x_img,y_img):
    image_box =  OffsetImage(im, zoom = 0.03) #container for the image
    ab = AnnotationBbox(image_box, (x, y), frameon = False)
    ax.add_artist(ab)


# Change x-axis tick spacing
ax.set_ylim(0,15)
ax.set_xlim(0,15)

ax.xaxis.set_ticks(np.arange(0, 20, 5), )
ax.yaxis.set_ticks(np.arange(0, 20, 5), )
ax.tick_params(axis='both', which='major',length=0, labelsize=12,colors =xy_ticklabel_color)
ax.grid(color = grid_color)
ax.set_xlabel(df.year.min(), size = 12, color = xlabel_color, weight = "bold")
ax.set_ylabel(df.year.max(), size=12, color = xlabel_color, weight= "bold")
for axis in ['top', 'bottom', 'left', 'right']:
    ax.spines[axis].set_color(grid_color) 
    ax.spines[axis].set_zorder(0)

The result:

93 of 100: Donut 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