Print

77 of 100: Tabular 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:

from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from matplotlib import pyplot as plt
import pandas as pd

Generate the data

We are hardcoding the data for now, so we jump straight to the code.

Plot the chart

fig, ax = plt.subplots(figsize=(8,6))

rows = 4
cols = 6
ylabel = ["Biggest % change","Biggest change","Most in 2022","Most in 2004"]
colors = [['w','r','w','r','#2B314D','w'],['w','r','w','r','#2B314D','w'],['w','r','#5375D4','w','w','#5375D4'],['#2B314D','w','#5375D4','w','w','#5375D4']]
positions = [ 0.5, 1.5, 2.5, 3.5,4.5,5.5]
img = [plt.imread("flags/no-sq.png"),plt.imread("flags/de-sq.png"), plt.imread("flags/sw-sq.png"),plt.imread("flags/de-sq.png"),plt.imread("flags/no-sq.png"),plt.imread("flags/sw-sq.png")]


# create a coordinate system based on the number of rows/columns
# adding a bit of padding on bottom (-1), top (1), right (0.5)

ax.set_ylim(-1, rows + 1)
ax.set_xlim(0, cols + .5)

for pos, im in zip(positions,img):

    image_box =  OffsetImage(im, zoom = 0.04) #container for the image
    ab = AnnotationBbox(image_box, (pos,4.6 ), frameon = False)
    ax.add_artist(ab)

# Add table's main text
for i, color in zip(range(rows), colors):
    #print(color)
    newaxes = []
    for c, (j, column) ,  in zip( color,enumerate(range(cols))):
        #print(j[::2])
        ax.scatter( positions[j], i,s = 100, c= c)

# Add dividing lines
for vline in range(0, cols+2 ,2):
    ax.axvline(x = vline, ymin = 0,ymax =1 , color = 'lightgrey')
    
for dotted_line in range(1, cols ,2):
    ax.axvline(x = dotted_line, ymin = 0,ymax =0.85 , ls = "dotted" , color = 'lightgrey')
    ax.annotate("VS.", xy =(dotted_line,4.5 ), ha = "center" ) 
    
ax.tick_params(axis='both', which='both',length=0, color = 'lightgrey',pad = 20)
ax.spines[['top', 'left','bottom', 'right']].set_visible(False)
ax.yaxis.set_ticks(range(rows), labels =ylabel)
ax.xaxis.set_ticks([])

The result:

77 of 100: Tabular 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