Print

61 of 100: Tally 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 need the following packages:

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
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.

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

Define the variables

 years = df.year.unique()
countries = df.countries.unique()

nr_bars =14

colors_sw = ["#5375D4"]*4 + ['w'] + ["#5375D4"]*4 + ['w'] + ["#5375D4"]*3 +["#7296E9"] 
colors_dk = ["#CC5A43"]*4 + ['w'] + ["#D57968"]*4 + ['w'] *5 
colors_no = ["#2C324F"]*4 + ['w'] + ["#464B64"]*3 + ['w'] *6 
crossed_colors_sw = ['#5375D4']*2+ ["#7296E9"]*1
crossed_colors_dk =  ["#D57968"]*2 + ['w']
crossed_colors_no =  ["#2C324F"]*1

y = [[0,3]]*nr_bars
x= [[y  for x in range(2)] for y in range(nr_bars)]

x_crossed = [[0,1,2,3], [5,6,7,8], [10,11,12,13]]

Plot the chart

fig, ax = plt.subplots(nrows=3, figsize=(5,5),facecolor = "#FFFFFF")
     
for  y, x, csw, cdk, cno in zip(y,x, colors_sw,colors_dk,colors_no ):
    ax[0].plot( x, y,'-', lw = 12, solid_capstyle="round",color = csw)
    ax[1].plot( x, y,'-', lw = 12, solid_capstyle="round",color = cdk)
    ax[2].plot( x, y,'-', lw = 12, solid_capstyle="round",color = cno)
    

for xc,ccsw, ccdk in zip(x_crossed, crossed_colors_sw,crossed_colors_dk):
    ax[0].plot(xc, list(range(4)), '-', lw = 12, solid_capstyle="round",color=ccsw ) 
    ax[1].plot(xc, list(range(4)), '-', lw = 12, solid_capstyle="round",color=ccdk ) 

for xc,ccno in zip(x_crossed[:2], crossed_colors_no):
    ax[2].plot(xc, list(range(4)), '-', lw = 12, solid_capstyle="round",color=ccno ) 


for r, country in zip(range(3), countries):
    ax[r].set_ylim(-1,4)
    ax[r].set_ylabel(country, rotation=0)
    ax[r].yaxis.set_label_coords(-0.2,0.4)
    ax[r].tick_params(axis='both', which='major', length=0, )
    ax[r].set_xticklabels([])
    ax[r].set_yticklabels([])
    ax[r].spines[['right','left','top','bottom']].set_visible(False)

#################
# add legend
##################

text_legends = ["Before", "After"]
colors = ["#5375D4","#7296E9",]
lines = [Line2D([0], [0], color=c, linestyle='-', ) for c in colors]
labels  = [f'{text_legend} 2004' for year, text_legend in zip(years, text_legends)]
for year in years:
    plt.figlegend( lines,labels,   
                  labelcolor="#454A58",
            bbox_to_anchor=(0.5, -0.05), loc="lower center",
                ncols = 2,frameon=False, fontsize= 10)

The result:

61 of 100: Tally 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