23 of 100: Stacked bar chart on a map 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 black box rounding the grand totals is not correct and the text legend needs to be on top of the lines.
This is the original viz that we are trying to recreate in matplotlib:

Import the packages
We will need the following packages:
import geopandas as gpd
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
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: "#5375D4", 2004: "#CC5A43", }
xy_ticklabel_color,color_map ='#101628','#D3D3D3'
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 create the subtotals for each year, the difference between sites by year, the country codes and then sort the data.
df['diff']=df.groupby('countries')['sites'].diff().fillna(df.sites).astype(int)
df['sub_total'] = df.groupby('countries')['diff'].transform('sum')
df = df.sort_values([ 'year', 'sub_total'], ascending=True ).reset_index(drop=True)
df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
df['color']= df.year.map(color_dict)
index | year | countries | sites | diff | sub_total | ctry_code | color |
---|---|---|---|---|---|---|---|
0 | 2004 | Norway | 5 | 5 | 8 | NO | #CC5A43 |
1 | 2004 | Denmark | 4 | 4 | 10 | DE | #CC5A43 |
2 | 2004 | Sweden | 13 | 13 | 15 | SW | #CC5A43 |
3 | 2022 | Norway | 8 | 3 | 8 | NO | #5375D4 |
4 | 2022 | Denmark | 10 | 6 | 10 | DE | #5375D4 |
5 | 2022 | Sweden | 15 | 2 | 15 | SW | #5375D4 |
Load map data
#load the map
map_df = gpd.read_file("https://raw.githubusercontent.com/eurostat/Nuts2json/master/pub/v2/2021/3035/20M/0.json")
# add a country column
map_df['country'] = map_df['id'].astype(str).str[:2]
#filter by nordic countries
map_df = map_df[map_df.country.isin(['NO','SE', 'DK']) ]
index | id | na | geometry | country |
---|---|---|---|---|
11 | DK | Danmark | MULTIPOLYGON (((4649929.995 3564341.094, 46459… | DK |
21 | SE | Sverige | MULTIPOLYGON (((4968534.919 4802763.317, 49724… | SE |
26 | NO | Norge | MULTIPOLYGON (((5002725.191 5305903.887, 49921… | NO |
Define the variables
lat= [0.42,0.48,0.54]
lon =[0.24,0.14,0.28]
x = len(df.year.unique())
countries = df.countries.unique()
totals = df.sub_total.unique()
codes = df.ctry_code.unique()
colors = df.color.unique()
Plot the chart
fig = plt.figure(figsize=(15,10))
ax_map = fig.add_axes([0, 0, 1, 1])
map_df.plot(color='#D3D3D3',ax=ax_map)
ax_map.set_axis_off()
for lt,ln,country, total, code in zip(lat,lon,countries, totals, codes):
print(lat, lon)
ax_bar = fig.add_axes([lt ,ln , 0.03, 0.2])
data = df[df["countries"] == country]
years= data.year
#add grand totals
ax_bar.text(0, total+1, total, ha= "center", color = "white",
bbox=dict(facecolor='black', edgecolor='black', boxstyle='round,pad=0.3'))
#add x label
ax_bar.set_xlabel(code, color =xy_ticklabel_color, size =14, weight= "bold")
bottom = np.zeros(x)
for year, color in zip(years, colors):
y = data[data.year == year].sort_values("sub_total", ascending = True)["diff"].values
ax_bar.bar(range(1), y, bottom = bottom, width= 0.2, color=color)
bottom +=y
ax_bar.set_ylim(0,15)
ax_bar.set_yticklabels([])
ax_bar.set_xticklabels([])
ax_bar.grid(False)
ax_bar.set_frame_on(False)
ax_bar.tick_params(axis='both', which='both',length = 0)
offset_text = 0.3
for bar,c in zip(ax_bar.patches, color):
ax_bar.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='w', size=8 )
#################
# add legend
##################
text_legends = ["Before 2004", "After 2004", "Total"]
colors = ["#5475D6","r", "black"]
lines = [Line2D([0], [0], color=c, linestyle='-', ) for c in colors]
labels = [f'{text_legend}' for text_legend in text_legends]
plt.figlegend( lines,labels,
labelcolor=xy_ticklabel_color,
bbox_to_anchor=(0.8, -0.05), loc="lower center",
ncols = 3,frameon=False, fontsize= 12)
The result:

Reader Interactions