Print

91 of 100: Nested proportional area charts 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
import matplotlib.patches as patches
import matplotlib as mpl
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",
              }
code_dict = {"Norway": "NO", "Denmark": "DK", "Sweden": "SE", }

xy_ticklabel_color, xlabel_color, grand_totals_color, legend_color, grid_color, datalabels_color ='#101628',"#101628","#101628","#101628", "#C8C9C9", "#757C85"


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

We need to create the country codes, colors and then sort the data.


df['ctry_code'] = df.countries.map(code_dict)
df = df.sort_values(['countries' ,'sites' ], 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 length and height of the rectangles.
df['sq_sites'] = (df['sites'])**.5
df['year_lbl'] ="'"+df['year'].astype(str).str[-2:].astype(str)
yearcountriessitesctry_codecolorsq_sitesyear_lbl
02022Sweden15SE#C4D6F83.872983’22
12004Sweden13SE#5375D43.605551’04
22022Norway8NO#9194A32.828427’22
32004Norway5NO#2B314D2.236068’04
42022Denmark10DK#E2AFA53.162278’22
52004Denmark4DK#A548362.000000’04

Define the variables

countries = df.countries.unique()
year_labels = df.year_lbl.unique()

# Generate 10 plots in a grid with 3 rows, 5 columns
x = [0,0.4,0.2]
y = [0.8,0.8, 1.2]

Plot the chart

fig = plt.figure(figsize=(5, 5),)


for x,y,country  in zip(x,y,countries):
    temp_df = df[df.countries==country]
    sites= temp_df.sites
    sq_sites = temp_df.sq_sites
    max_sites =sq_sites.max()
    codes = temp_df['ctry_code'].unique()
    colors =temp_df.color
    ax= fig.add_axes([x, y, 0.5, 0.5], )
    ax.text(0,max_sites/2, codes[0] , color ="w",ha="center", va="center")
    ax.text(0,-0.5, sites[1:].item() , color =colors[1:].item(),ha="center", va="center")
    ax.text(0,max_sites +2  , sites[:-1].item() , color =colors[:-1].item(),ha="center", va="center")

    for sq_site,color in zip(sq_sites,colors):
        r1 = patches.Rectangle((0,0), sq_site, sq_site, color=color )
        t2 = mpl.transforms.Affine2D().rotate_deg(45) + ax.transData
        r1.set_transform(t2)
        ax.add_patch(r1)
        ax.set_xlim(-5,5)
        ax.set_ylim(-0,10)
        
        ax.set_yticklabels([])
        ax.set_xticklabels([])
        ax.set_frame_on(False)
        ax.tick_params(axis='both', which='both',length = 0)


#add legend
lines = [Line2D([0], [0], color=c,  marker='d',linestyle='', markersize=8,) for c in colors.unique()]

plt.legend(lines, year_labels, labelcolor = grid_color,
           prop=dict( size=10), 
           bbox_to_anchor=(1.5, -1), loc="lower center",
            frameon=False, fontsize= 14)

The result:

91 of 100: Nested proportional area charts in matplotlib
Was this helpful?

Reader Interactions

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents