Print

9 of 100: Square 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!

To be improved: Hardcoding on the labels, should be possible to improve.

This is the original viz that we are trying to recreate in matplotlib:

Import the packages

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 = {"Norway": "#2B314D", "Denmark": "#A54836", "Sweden": "#5375D4", }

xy_ticklabel_color, grand_totals_color, datalabels_color ='#757C85',"#101628", "#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

I need to add three columns to the dataframe: Subtotals, percent change and country codes as well as sort the chart.

df = df.sort_values([ 'year'], ascending=True ).reset_index(drop=True)
df['sub_total'] = df.groupby('year')['sites'].transform('sum')
df['pct_group'] = 100 * df['sites'] / df.sub_total
df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
df['color']=df.countries.map(color_dict)
indexyearcountriessitessub_totalpct_groupctry_codecolor
02004Denmark42218.181818DE#A54836
12004Norway52222.727273NO#2B314D
22004Sweden132259.090909SW#5375D4
32022Denmark103330.303030DE#A54836
42022Norway83324.242424NO#2B314D
52022Sweden153345.454545SW#5375D4

Define the variables:

nr_years = df.year.unique() 
code = df.ctry_code.unique()
pct = df.pct_group.unique()
total = df.sub_total.unique()
colors = df.color.unique()

Plot the square chart

fig, axes = plt.subplots(ncols = df.year.nunique(), nrows = 1, figsize=(10,5),sharex=True, sharey=True, facecolor = "#FFFFFF", zorder= 1)
fig.tight_layout(pad=3.0)

for yr,tot, ax  in zip(nr_years,total, axes.ravel()):

    temp_df = df[df.year ==yr]
    y = temp_df.sub_total
    w = temp_df.pct_group.tolist()
   
    #get the new x position
    xticks=[]
    for n, c in enumerate(w):
        xticks.append(sum(w[:n]) + w[n]/2)   

    ax.bar(xticks, height = y, width = w, color = colors)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.spines[['left', 'top','bottom','right']].set_visible(False)
    
    for l1, l2, x in zip(code,pct, xticks):
        ax.text(x,1, l1, color = datalabels_color, weight= "bold", ha= "center", va="center")
        ax.text(x, 3,  f" {int(l2)}%",size = 12, weight= "light", color = datalabels_color,ha= "center", va="center")

    #add the grand totals
    ax.text(50,tot+4, tot, ha="center", color = grand_totals_color, size = 30, weight= "bold")
    #add the year labels
    ax.set_xlabel(yr, color = xy_ticklabel_color, size = 16)
    ax.xaxis.set_label_coords(0.5, -0.1)

The result:

9 of 100: Square 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