Print

25 of 100: 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!

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 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 = {"Norway": "#2B314D", "Denmark": "#A54836", "Sweden": "#5375D4", }

xy_label_color,   datalabels_color ='#757C85', "#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 subtotals for each year and then sort the data.

df['sub_total'] = df.groupby('countries')['sites'].transform('sum')
df = df.sort_values([ 'sub_total'], ascending=True ).reset_index(drop=True)
#map the colors of a dict to a dataframe
df['color']= df.countries.map(color_dict)
indexyearcountriessitessub_totalcolor
02004Norway513#2B314D
12022Norway813#2B314D
22004Denmark414#A54836
32022Denmark1014#A54836
42004Sweden1328#5375D4
52022Sweden1528#5375D4

Define the variables

nr_years = df.year.unique() 
colors = df.color.unique()
img = [plt.imread("flags/de-sq.png"),plt.imread("flags/no-sq.png"), plt.imread("flags/sw-sq.png")]

Plot the chart

fig, axes = plt.subplots(ncols = df.year.nunique(), nrows = 1, figsize=(7,5),sharex=True, sharey=True, facecolor = "#FFFFFF", zorder= 1)
fig.tight_layout(pad=3.0)

for yr, ax  in zip(nr_years, axes.ravel()):

    temp_df = df[df.year ==yr]
    x = temp_df.countries
    y = temp_df.sites
   
    ax.bar(x, height = y, width=1, align='edge',color = colors)

    for bar, site in zip(ax.patches, y):
         height = bar.get_height()
         ax.text(
            bar.get_x() + bar.get_width() / 2, 
            0.3 ,  #height
            site, ha="center", va="bottom",
            color = datalabels_color, weight= "light",
    )

     #set flags    
    ax.xaxis.set_ticks(x, ['', '', '']) 
    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.7, 2)
                        )
        ax.add_artist(ab)
    
  
    ax.set_yticklabels([])
    ax.tick_params(axis='both', which='both',length=0)
    ax.spines[['top', 'left','bottom', 'right']].set_visible(False)
    #add x labels
    ax.set_xlabel(yr,color = xy_label_color, size = 12)
    ax.xaxis.set_label_coords(0.5, -0.2)
  

The result:

Stacked 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