Print

27 of 100: Clustered 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: The colors and the x axis can be automated.

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.offsetbox import OffsetImage, AnnotationBbox
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 = {(2022,"Norway"): "#9194A3", (2004,"Norway"): "#2B314D",
              (2022,"Denmark"): "#E2AFA5", (2004,"Denmark"): "#A54836",
              (2022,"Sweden"): "#C4D6F8", (2004,"Sweden"): "#5375D4",
              }

xy_ticklabel_color, grid_color, datalabels_color ='#757C85', "#C8C9C9", "#2B314D"

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 subtotals for each year, year label and then sort the data.

df['year_lbl'] ="'"+df['year'].astype(str).str[-2:].astype(str)
sort_order_dict = {"Denmark":2, "Sweden":3, "Norway":1, 2004:5, 2022:4}
df = df.sort_values(by=['year','countries',], key=lambda x: x.map(sort_order_dict))
#Add the color based on the color dictionary
df['color'] = df.set_index(['year', 'countries']).index.map(color_dict.get)
indexyearcountriessitesyear_lblcolor
32022Norway8’22#9194A3
12022Denmark10’22#E2AFA5
52022Sweden15’22#C4D6F8
22004Norway5’04#2B314D
02004Denmark4’04#A54836
42004Sweden13’04#5375D4

Define the variables

countries = df.countries.unique()
x_axis = np.array(list(range(1,len(countries)+1))*2, dtype=float)
x_axis[0:3] += 0.2
labels = df.year_lbl
colors = df.color
img = [plt.imread("flags/no-rd.png"),plt.imread("flags/de-rd.png"), plt.imread("flags/sw-rd.png")]

Plot the chart

fig, ax = plt.subplots(figsize=(7,5),facecolor = "#FFFFFF")

ax.bar(x_axis, height =df.sites, width=0.5, color = colors,zorder= 2)

for bar, label in zip(ax.patches, labels):
    ax.text(
        bar.get_x() + bar.get_width() / 2, 
         bar.get_height() + bar.get_y()-1,
        label, ha="center", va="bottom", size = 12,
        color = "w", )
    
#set flags   
ax.xaxis.set_ticks([1,2,3],  labels =countries) 
tick_labels = ax.xaxis.get_ticklabels()

for i,im in enumerate(img):
    ib = OffsetImage(im, zoom=.04)
    ab = AnnotationBbox(ib,
                    tick_labels[i].get_position(),
                    frameon=False,
                    box_alignment=(0.5, 0.5)
                    )
    ax.add_artist(ab)

ax.yaxis.set_ticks(np.arange(0, 20, 5))
ax.tick_params(axis='both', which='both',length=0,labelsize=12,colors= xy_ticklabel_color, pad=20)  
ax.set_ylim(0, 17)
    
#ax.grid(True, axis='y', linestyle='solid',  linewidth=1, color = grid_color,zorder= 1)
ax.spines[['top','bottom','left','right']].set_visible(False)

# Customize the major grid
ax.grid(which='major', axis = "y", linestyle='-', linewidth='0.5', color=xy_ticklabel_color)
# Customize the minor grid
ax.grid(which='minor',axis = "y", linestyle='dotted', linewidth='0.5', color=grid_color)
ax.minorticks_on()

The result:

27 of 100: Clustered 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