100 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!
To be improved: I need to automate the creation of the sparklines. I have a way to create all the sub figures at once, but I dont know yet how to reference the new figures. Will review.
This is the original viz that we are trying to recreate in matplotlib:

Import the packages
We will need the following packages:
from matplotlib import pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
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" : ["Sweden", "Sweden", "Denmark", "Denmark", "Norway", "Norway"],
"sites": [13,15,4,10,5,8]
}
df= pd.DataFrame(data)
index | year | countries | sites |
---|---|---|---|
0 | 2004 | Sweden | 13 |
1 | 2022 | Sweden | 15 |
2 | 2004 | Denmark | 4 |
3 | 2022 | Denmark | 10 |
4 | 2004 | Norway | 5 |
5 | 2022 | Norway | 8 |
We need to pivot the table, create the change, in % and AVG columns and row and then sort the data.
df = df.pivot_table( index= 'countries', columns = 'year', values = 'sites').reset_index()
df.columns.name = None #FLATTEN THE PIVOT
df['Change']= df[2022]-df[2004]
df['in %'] = df.Change/df[2004]*100
df.loc['AVG.'] = df.mean(numeric_only=True)
df =df.fillna("Avg.").reset_index().drop(columns='index')
df = df.sort_index( ascending=False )
df['in %'] =df['in %'].astype('int').astype(str) +"%"
df[[2004, 2022, "Change"]] =df[[2004, 2022, "Change"]].astype('int').astype(str) #get rid of the decimals
index | countries | 2004 | 2022 | Change | in % |
---|---|---|---|---|---|
3 | Avg. | 7 | 11 | 3 | 75% |
2 | Sweden | 13 | 15 | 2 | 15% |
1 | Norway | 5 | 8 | 3 | 60% |
0 | Denmark | 4 | 10 | 6 | 150% |
Plot the chart
fig, ax = plt.subplots(figsize=(8,6))
rows = len(df.countries)
cols = len(df.columns[1:])
img = [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)
positions = [ 0.5, 1.5, 2.5, 3.5]
# Add table's main text
for i in range(rows):
newaxes = []
for j, column in enumerate(df.columns[1:]):
ax.annotate(
xy=(positions[j], i), weight = "bold", size= 12,
text=df[column].iloc[i],
va='center'
)
#add column headers
ax.annotate(xy = (positions[j],rows ), text = column, size = 14,color = "#818F9A", weight = "light")
# Add dividing lines
ax.plot([0, cols ],[i-.5, i- .5],ls='-',lw='.5',c='lightgrey')
ax.plot([0, cols ], [3.5, 3.5], lw='.5', c='lightgrey')
ax.set_axis_off()
#add flags
def ax_flag(img, ax,xy, x, y):
image_box = OffsetImage(img, zoom = 0.05) #container for the image
ab = AnnotationBbox(image_box, xy, xybox=(x, y), xycoords='data',
boxcoords="offset points",frameon = False)
ax.add_artist(ab)
postiony = [165, 110, 55]*3
for im, posy in zip(img, postiony):
ax_flag(im, ax, (0,0), 0,posy)
# I need to automate this
colors = ["#CC5A43","#2C324F","#5375D4","#B4BDC3" ]
sites_2004 =[4,5,13,7,]
sites_2022 =[10,8,15,11]
sites_change =[6,3,2,3]
sites_in =[150,60,15,75]
axes2004 = []
axes2022 = []
axesChange = []
axesIn = []
for row, color, s04,s22, sc, si in zip(range(rows), colors,sites_2004,sites_2022,sites_change,sites_in):
# offset each new axes by a set amount depending on the row
#[left, bottom, width, height]
# this is probably the most fiddly aspect (TODO: some neater way to automate this)
axes2004.append(
fig.add_axes([0.21, .57 - (row*.13), .12, .03]))
axes2022.append(
fig.add_axes([0.38, .57 - (row*.13), .12, .03]))
axesChange.append(
fig.add_axes([0.55, .57 - (row*.13), .12, .03]))
axesIn.append(
fig.add_axes([0.73, .57 - (row*.13), .12, .03]))
axes2004[row].barh(y=.5, width=s04, height=.3, color = color, alpha=.85)
axes2004[row].axis('off')
axes2004[row].set_xlim(0, 15)
axes2022[row].barh(y=.5, width=s22, height=.3, color = color, alpha=.85)
axes2022[row].axis('off')
axes2022[row].set_xlim(0, 15)
axesChange[row].barh(y=.5, width=sc, height=.3, color = color, alpha=.85)
axesChange[row].axis('off')
axesChange[row].set_xlim(0, 15)
axesIn[row].barh(y=.5, width=si, height=.3, color = color, alpha=.85)
axesIn[row].axis('off')
axesIn[row].set_xlim(0, 150)
ax.annotate("Avg.", xy= (0,-0.1), size= 16, color = "#B4BDC3" )
The result:

Reader Interactions