Print

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

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

Watch me build it or keep on reading:

Viz 1 - 1 dataset, 100 matplotlib viz : Stacked bar chart

If you prefer to read, keep scrolling:

Import the packages

We will need the following packages:

import matplotlib.pyplot as plt
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 = {"Norway": "#2B314D", "Denmark": "#A54836", "Sweden": "#5375D4", }
xylabel_color, grand_totals_color, grid_color, datalabels_color ='#757C85',"#101628", "#C8C9C9", "w"

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

We need to create the subtotals for each year and then we custom sort the data.

df['sub_total'] = df.groupby('year')['sites'].transform('sum')
#custom sort
sort_order_dict = {"Denmark":2, "Sweden":3, "Norway":1, 2004:4, 2022:5}
df = df.sort_values(by=['year','countries',], key=lambda x: x.map(sort_order_dict))
#map the colors of a dict to a dataframe
df['color']= df.countries.map(color_dict)
yearcountriessitessub_totalcolor
42004Norway522#2B314D
22004Denmark422#A54836
02004Sweden1322#5375D4
52022Norway833#2B314D
32022Denmark1033#A54836
12022Sweden1533#5375D4

Define the variables

unique_countries = df.countries.unique()
years = df.year.unique()
colors = df.color
sub_total = df.sub_total.unique()

Plot the stacked bar chart

Now we are ready to plot the stacked bar chart.

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


bottom = np.zeros(len(years))
for country, color  in zip(unique_countries, colors):
    y = df[df["countries"] == country]["sites"].to_numpy()
    ax.bar(range(len(years)), y, bottom = bottom,  width= 0.6, color=color)
    bottom +=y

# Show sum on each stacked bar
for i, total in enumerate(sub_total):
    ax.text(i, total+1 , total, ha='center', size = 20, color = grand_totals_color) #weight='bold')

#add data labels
for bar in ax.patches:
    ax.text(
        bar.get_x() + bar.get_width() / 2,            # Put the text in the middle of each bar. get_x returns the start, so we add half the width to get to the middle.
        bar.get_height()/2 + bar.get_y(),              # Vertically, add the height of the bar to the start of the bar,  along with the offset.   
        round(bar.get_height()),                          # This is actual value we'll show.
        ha='center', color=datalabels_color,  size=16  )

#add country legend at the end bar only 
offset_text = 1
for bar, country,  color in zip(ax.patches[len(years)-1::len(years)], unique_countries,  colors):  #get every other element skip one
    ax.text(
        bar.get_x() + bar.get_width() + offset_text, 
        bar.get_height()/2 + bar.get_y(),
        country,
        ha='center', color=color,  size=16 )

# We change the fontsize of minor ticks label 
ax.tick_params(axis='both', which='major', length=0, labelsize=16,colors= xy_ticklabel_color,pad =15)
ax.xaxis.set_ticks(range(len(years)), labels =years)

#add vertical grid lines
ax.set_axisbelow(True) #set the grid lines in the BACK
ax.grid(True, axis='y', linestyle='solid',  linewidth=1, color = grid_color)
ax.set_xlim(-1,len(years))
ax.set_ylim(0,df.sub_total.max()+4)
ax.spines[['left', 'right', 'top', 'bottom']].set_visible(False)


import IPython 
s = IPython.extract_module_locals()[1]['__vsc_ipynb_file__']
filename = str( s[s.find("dataviz\\")+len("dataviz\\"):s.rfind(".ipynb")])
fig.savefig(r'C:/Users/Ruth Pozuelo/Documents/SynologyDrive/Matplotlib-Labs/100 dataviz/0.Images/' + filename +'.png',
            bbox_inches = 'tight', facecolor=fig.get_facecolor(), transparent=False, dpi = 600)

The result:

1 of 100: 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