Print

15 of 100: Progress 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 use Line2D to add the legend.

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
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 = {"Norway": "#2B314D", "Denmark": "#A54836", "Sweden": "#5375D4","AVG.":"#838B93" }

xy_ticklabel_color, title_color, grid_color,  ='#C8C9C9',"#838B93", "#C8C9C9", 

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 country codes and year labels:

df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
df['year_lbl'] ="'"+df['year'].astype(str).str[-2:].astype(str)
yearcountriessitesctry_codeyear_lbl
02004Denmark4DE’04
12022Denmark10DE’22
22004Norway5NO’04
32022Norway8NO’22
42004Sweden13SW’04
52022Sweden15SW’22

Add the AVG. column

It is probably best to add the AVG. column using numpy but I have done it with pandas first.

df2 = df.groupby('year')['sites'].transform('mean').astype(int).drop_duplicates().reset_index()
df2[['ctry_code','countries']] = "AVG."
df2['year'] = [2004,2022]
df3 = pd.concat([df,df2],ignore_index = True)
df3['color']= df3.countries.map(color_dict)
#custom sort
sort_order_dict = {"Denmark":2, "Sweden":1, "Norway":3, "AVG.":4, 2004:4, 2022:5}
df3 = df3.sort_values(by=['countries','year',], key=lambda x: x.map(sort_order_dict))
yearcountriessitesctry_codeyear_lblindex
02004Denmark4DE’04NaN
12022Denmark10DE’22NaN
22004Norway5NO’04NaN
32022Norway8NO’22NaN
42004Sweden13SW’04NaN
52022Sweden15SW’22NaN
62004AVG.7AVG.NaN0.0
72022AVG.11AVG.NaN1.0

Define the variables

countries = df3.countries.unique()
codes= df3.ctry_code.unique()
colors = df3.color.unique()

Plot the chart

fig, axes = plt.subplots(ncols = len(countries), nrows =1,  figsize=(6, 6), sharey=True)
fig.tight_layout(pad=2.0)

for country, code, color, ax in zip(countries, codes,colors, axes.ravel()):
    temp_df= df3[df3.countries==country]
    temp_site = temp_df.sites
    for site,year in zip(temp_df.sites, temp_df.year):
        ax.axhline(y= site, lw=4, color=color)
        if year == 2004:
            ax.text(0.5,site - 0.3  , year, ha= "center", va = "top", size = 12,color= color, alpha = 0.5)
        else:
            ax.text(0.5,site + 0.3 , year, ha= "center", va="bottom", size = 12,color= color, alpha = 0.5)

    
    ax.annotate("", xy = (0.5, temp_site.max()), xytext=(0.5, temp_site.min()),
                color='w', weight= "bold",
        arrowprops=dict( arrowstyle='->',color = color, lw=1 ) )

    ax.set_xticks([])
    ax.set_ylim(0,16)
    ax.set_frame_on(False) 
    ax.tick_params(axis='both', which='major',length=0, labelsize=12,colors= xy_ticklabel_color, pad= 10)

    #add vertical grid lines
    ax.grid(True, axis='y', linestyle='solid',  linewidth=1, color = grid_color)

    ax.set_title(code,color= title_color,x=0.5, y=1.05, size=12, )

The result:

15 of 100: Progress 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