Print

12 of 100: Nested Proportional Area 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 matplotlib, and pandas.

import matplotlib.pyplot as plt
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_label_color, legend_color,  datalabels_color ='#101628',"#757C85", "#FFFFFF"

data = {
    "year": [2004, 2022, 2004, 2022, 2004, 2022],
    "countries" : [ "Denmark", "Denmark", "Norway", "Norway","Sweden", "Sweden",],
    "sites": [4,10,5,8,13,15]
}
df= pd.DataFrame(data)
Indexyearcountriessites
02004Sweden13
12022Sweden15
22004Denmark4
32022Denmark10
42004Norway5
52022Norway8

Then we need to add the colors and sort:

df = df.sort_values([ 'year'], ascending=False ).reset_index(drop=True)
#Add the color based on the color dictionary
df['color'] = df.set_index(['year', 'countries']).index.map(color_dict.get)
#To ensure that the areas are really proportional, use the square root values as the radius of the circles.
df['radius'] = (df['sites'])**.5
yearcountriessitescolorradius
02022Denmark10#E2AFA53.162278
12022Norway8#9194A32.828427
22022Sweden15#C4D6F83.872983
32004Denmark4#A548362.000000
42004Norway5#2B314D2.236068
52004Sweden13#5375D43.605551

Define the variables

nr_plots = df.countries.nunique()
countries =df.countries.unique()
labels = df.year.unique()

Plot the Proportional area chart

nr_plots = df.countries.nunique()
countries =df.countries.unique()
labels = df.year.unique()

fig, axes = plt.subplots(ncols=1, nrows=nr_plots, figsize=(10,5), sharex=True, sharey=True, facecolor= "white")
fig.tight_layout(pad=1.0)


for country,  ax in zip(countries,  axes.ravel()):
    
    radius = df[df.countries==country]["radius"].values
    sites =  df[df.countries==country]["sites"].values
    colors =  df[df.countries==country]["color"].values

    for n, (site,rad, color), in enumerate(zip(sites,radius, colors)):
        circle = plt.Circle((0, rad), color=color,radius=rad )
        ax.add_artist(circle)
        ax.set_xlim(-5, 5)
        ax.set_ylim(0,10)
        ax.set_aspect('equal')
        #add x labels
        ax.set_xlabel(country, color =xy_label_color, size=10)
        ax.set_yticklabels([])
        ax.set_xticklabels([])
        ax.set_frame_on(False)
        ax.tick_params(axis='both', which='both',length = 0)
    
for site04, rad04,site22, rad22, ax in zip(df.sites[-3:], df.radius[-3:],df.sites[:3], df.radius[:3],axes.ravel()):
        print(site22)
        #add data labels
        ax.annotate(site04, xy=(0, rad04), fontsize=10, color = datalabels_color, ha = "center", va="center",transform=ax.transAxes)
        ax.annotate(site22, xy=(0, rad22*2), fontsize=10, color = datalabels_color, ha = "center", va="top",transform=ax.transAxes)


#add legend
plt.figlegend( labels,
        handlelength=2,  #hide marker
        bbox_to_anchor=(0.6, 0), loc="lower left",
        frameon=False, fontsize= 10, labelcolor = legend_color)

The results:

12 of 100: Nested Proportional Area 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