Print

20 of 100: Packed circle 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 have missing things here, the packing of the bubbles and the curved text. Will review.

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

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.

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 add the colors, the difference between the sites 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['new_sites'] =  np.where((df['year'] == 2004), df.sites, df['diff'])
df['colors']=["#5375D4","#A54836","#2B314D","#5375D4","#A54836","#2B314D"]
indexyearcountriessitesdiffnew_sitescolors
02004Sweden1313.013.0#5375D4
12004Denmark44.04.0#A54836
22004Norway55.05.0#2B314D
32022Sweden152.02.0#5375D4
42022Denmark106.06.0#A54836
52022Norway83.03.0#2B314D

Define the variables

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

#define the axes
yposition = [0.31,0.21]
height = [0.4,0.6]
origins = [0,-2]

Plot the chart

fig, ax = plt.subplots(figsize=(6, 6))
fig.tight_layout(pad=3.0)

for  year, origin,  ypos, h, in zip( years, origins, yposition, height,):
        #add to concentric axes
        ax_pie = fig.add_axes([0.22, ypos, 0.6, h], polar=True)
        ax_pie.set_rorigin(origin)
        ax_pie.set_theta_zero_location("N")
        ax_pie.set_theta_direction(-1)
        temp_df =df[df["year"] == year]
        new_sites = temp_df['new_sites'].astype(int)   
        ax_pie.grid(False)
        ax_pie.set_xticklabels([])
        ax_pie.set_yticklabels([])
        ax_pie.spines['inner'].set_color('#798085')
        ax_pie.spines['polar'].set_color('#798085')
        
        for site,c in zip(new_sites, temp_df.colors):
                r = np.random.rand(site)
                theta = 2 * np.pi * np.random.rand(site)
                ax_pie.scatter(theta,r, c=c,clip_on= True)



ax.set_axis_off() 
                
plt.annotate("2022", (-0.1,0.92), annotation_clip=False, 
             bbox = dict(fc="w", ec="w"))  
plt.annotate("2004", (-0.1,-0.1), annotation_clip=False, 
             bbox = dict(fc="w", ec="w"))        

The result:

20 of 100: Packed circle 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