Print

36 of 100: Linked bar 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 sankey effect 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 = { 2004: "#A54836", 2022: "#5375D4", }

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

We need to create the country codes, year labels, percentage change and then sort the data.

df['pct_change'] = df.groupby('countries', sort=False)['sites'].apply(
     lambda x: x.pct_change()).to_numpy().round(3)*100

df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
df['year_lbl'] ="'"+df['year'].astype(str).str[-2:].astype(str)

sort_order_dict = {"Denmark":3, "Sweden":2, "Norway":1, }
df = df.sort_values(by=['countries',], key=lambda x: x.map(sort_order_dict))
#map the colors of a dict to a dataframe
df['color']= df.year.map(color_dict)
indexyearcountriessitespct_changectry_codeyear_lblcolor
22004Norway5NaNNO’04#A54836
32022Norway860.0NO’22#5375D4
42004Sweden13NaNSW’04#A54836
52022Sweden1515.4SW’22#5375D4
02004Denmark4NaNDE’04#A54836
12022Denmark10150.0DE’22#5375D4

Define the variables

countries = df.countries.unique()
sites = df.sites
years = df.year
#if it is a whole number remove the decimals otherwise keep it.
pcts = [int(num) if float(num).is_integer() else num for num in df["pct_change"]]
colors = df.color
space_btw_subplots = 0.6

Plot the chart

fig, axes = plt.subplots(nrows=3, sharey=True, ncols=2,figsize=(8, 8))
plt.subplots_adjust(hspace=0.4, wspace= space_btw_subplots)

for site,color, ax in zip(sites, colors,  axes.ravel()):

    ax.bar([1], site, width = 10, color = color)

    ax.text(0.5,1.2, f'{site}',size=14, weight = "bold", ha = "center", va = "center", transform = ax.transAxes)
    ax.text(0.5,1.05, f'World Heritage Sites',size=10, ha = "center", transform = ax.transAxes)
    ax.axvline(0,0,1.4, color = 'lightgrey', lw= 1, clip_on = False)
    ax.axvline(1,0,1.4, color = 'lightgrey', lw= 1, clip_on = False)

    ax.set_yticklabels([])
    ax.set_xticklabels([])
    ax.set_xlim(0,1)
    ax.spines[['top', 'bottom', 'left','right']].set_visible(False)
    ax.tick_params(length=0, )

for ax, country,pct in zip(axes[:,0], countries, pcts[1::2]):
    ax.set_ylabel(country, rotation=0,size= 12, color =xy_ticklabel_color)
    ax.yaxis.set_label_coords(-0.2, 0.5)
    ax.text(1 + space_btw_subplots/2,1.2, f'{pct}%', size= 12, weight= "bold", ha = "center", transform = ax.transAxes)
    ax.text(1 + space_btw_subplots/2,1.05, f'Increase', size= 10, ha = "center", transform = ax.transAxes)

for ax, year in zip(axes[0], years):
    ax.set_title(year, x=0.55, y=1.5, color= xy_ticklabel_color) 

The result:

36 of 100: Linked bar 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