Print

85 of 100: Timeline 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 still need to add the arches between the bars.

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.

color_dict = {"Norway": "#2B314D", "Denmark": "#A54836", "Sweden": "#5375D4", }
code_dict = {"Norway": "NO", "Denmark": "DK", "Sweden": "SE", }

xy_ticklabel_color,  bar_color, datalabels_color ='#CAD2D8', "#eeeeee", "#FFFFFF"

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 country code, percentage change and then sort the data.

df['ctry_code'] = df.countries.map(code_dict)
df = df.sort_values([ 'year'], ascending=True ).reset_index(drop=True)
df['pct_change'] = df.groupby('countries', sort=False)['sites'].apply(
     lambda x: x.pct_change()).to_numpy()*100
df['pct_change'] = df['pct_change'].fillna(0.0).astype(int)
df['pct_change'] = np.where(df['pct_change']==0, "", df['pct_change'].astype(str)+"%")
#map the colors of a dict to a dataframe
df['color']= df.countries.map(color_dict)
yearcountriessitesctry_codepct_changecolor
02004Sweden13SE#5375D4
12004Denmark4DK#A54836
22004Norway5NO#2B314D
32022Sweden15SE15%#5375D4
42022Denmark10DK150%#A54836
52022Norway8NO60%#2B314D

Define the variables

years = df.year.unique()
colors = ["#CC5A43","#2C324F","#5375D4"]

Plot the chart

fig, axes = plt.subplots(nrows = len(years), figsize=(15,5))
fig.subplots_adjust(hspace=3.5)

lines = np.arange(0,21)
for ax,year in zip(axes.ravel(), years):
    ax.broken_barh([(0, 20)], (0, 0.2), color = bar_color)
    #Break the bars with lines
    for line in zip(lines):
        ax.axvline(x=line, ymin = 0, ymax = 0.2, color=xy_ticklabel_color, linestyle= "-") 
    #add annotations
    temp_df = df[df.year==year]
    for site, code, pct, c in zip(temp_df.sites, temp_df.ctry_code,temp_df['pct_change'],colors):
        ax.annotate(pct , xy = (site-0.3, 1.5), color = c, weight= "bold", annotation_clip=False)
        ax.annotate(code, xy = (site, 1), color=datalabels_color, weight= "bold", ha="center",
            bbox=dict(ec =c, boxstyle='round,pad=0.5', fc = c),
            arrowprops=dict( arrowstyle='-',color = c ), annotation_clip=False )
        ax.text( site,0.7,"\u25BC", size= 12, color = c,ha="center",)
        ax.axvline(x=site, ymin = 0, ymax =0.7, color=c, linestyle= "-",clip_on = False) 
    
    ax.set_ylim(0,1)
    ax.set_xlim(0,20)

    ax.xaxis.set_ticks(np.arange(0, 25, 5), labels = [0,5,10,15,20])
    ax.yaxis.set_ticks(np.arange(0, 1, 1), labels = [])

    ax.tick_params(axis='both', which='major',length=0, labelsize=12,colors =xy_ticklabel_color)
    ax.spines[["bottom",'top','left','right']].set_visible(False)
    
    #add the y lables
    ax.set_ylabel(year, rotation =0, labelpad=16, color=xy_ticklabel_color,)
    ax.yaxis.set_label_coords(-0.02,0.02)
    

The result:

85 of 100: Timeline 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