Print

6 of 100: Horizontal Stacked 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 annotations can be also automated. Will revisit later.

This is the original viz that we are trying to recreate in matplotlib:

Import the packages

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

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_bar = {(2022,"Norway"): "#9194A3", (2004,"Norway"): "#2B314D",
              (2022,"Denmark"): "#E2AFA5", (2004,"Denmark"): "#CE5A43",
              (2022,"Sweden"): "#C4D6F8", (2004,"Sweden"): "#5375D4",
              }

color_dict_edges = {(2022,"Norway"): "#2C324F", (2004,"Norway"): "#1B203A",
              (2022,"Denmark"): "#CE5A43", (2004,"Denmark"): "#B6493F",
              (2022,"Sweden"): "#5375D4", (2004,"Sweden"): "#4562C5",
              }
xy_ticklabel_color, grand_totals_color, grid_color, datalabels_color ='#757C85',"#101628", "#C8C9C9", "#FFFFFF"

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)
yearcountriessites
02004Sweden13
12022Sweden15
22004Denmark4
32022Denmark10
42004Norway5
52022Norway8

We need to create the subtotals for each year so we use pandas groupby and then sort the data.

#Add the color based on the color dictionary
df['color_bars'] = df.set_index(['year', 'countries']).index.map(color_dict_bar.get)
df['color_edges'] = df.set_index(['year', 'countries']).index.map(color_dict_edges.get)

df['sub_total'] = df.groupby('countries')['sites'].transform('sum')
df = df.sort_values([ 'year', 'sub_total'], ascending = False).reset_index(drop=True)
indexyearcountriessitescolor_barscolor_edgessub_total
02022Sweden15#C4D6F8#5375D428
12022Denmark10#E2AFA5#CE5A4314
22022Norway8#9194A3#2C324F13
32004Sweden13#5375D4#4562C528
42004Denmark4#CE5A43#B6493F14
52004Norway5#2B314D#1B203A13

Define the variables:

The x and y axis have been hardcoded, but it can be automated. Will revisit later.

year = df.year.unique()
sites = df.sites

img = [plt.imread("flags/sw-rd.png"),plt.imread("flags/de-rd.png"), plt.imread("flags/no-rd.png")]

#define the colors
colors_bars = df.color_bars
color_bar_end_circles = df.color_bars[:3].tolist()  + df.color_bars[-3:].to_list()*2
color_edge_end_circles =   ['w'] + df.color_edges[1:3].to_list() +  ['w'] + df.color_edges[4:6].to_list() 
edge_colors = df.color_edges

#define the x and y axes - the position of the circles
x = df.sites.tolist() + [0]*len(countries)
y=list(range(len(countries)))*len(countries)

Plot the stacked bar chart

This can be further improved with the annotations and the end of the bars. Will check it out in the next round.

fig, ax = plt.subplots(figsize=(10,4), facecolor = "w")

#plot all the circles at the end of the bars
ax.scatter(x,y, marker="o",s=620, color=color_bar_end_circles, zorder=2)

#plot the data label circles
ax.scatter(x[:6],y[:6], marker="o",s=450, color=edge_colors, ec =color_edge_end_circles, zorder=2)

#plot the bars
for i, col in enumerate(year):
    temp_df = df[df.year==col]
    ax.barh(temp_df.countries, temp_df.sites, height=0.3,  zorder=1,)

#plot the color of the bars and the data labels
for bar,color in zip(ax.patches,colors_bars):
    bar.set_facecolor(color)
    ax.text(
        bar.get_x() + bar.get_width() ,
        bar.get_height()/2 + bar.get_y(),
        round(bar.get_width()),
        ha='center',va="center", color='w',  size=10 )

#format the plot
ax.set_xlim(-1)   
ax.set_xticks([])   
ax.spines[['left', 'right','top','bottom']].set_visible(False)

#set flags    
ax.yaxis.set_ticks(range(3), countries,weight = "bold", ha="left") 
ax.tick_params(axis='y', which='major', labelsize=14,  colors= '#101628',length=0,pad=65)  
tick_labels = ax.yaxis.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=(+7, +0.5)
                    )
    ax.add_artist(ab)


for site, year in zip(sites[0::3], year):
    #add the annotations at the end of the first bar chart.
    ax.annotate(year, xy = (site, -0.13), xytext=(site, -.55),
                color='black', ha= "center", va="center",
            bbox=dict(facecolor='none', edgecolor='#DEE2E4', boxstyle='round,pad=0.5'),
            arrowprops=dict( arrowstyle='-',color = "#DEE2E4" ) ,
         annotation_clip=False)

The result:

6 of 100: Horizontal 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