99 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!
To be improved: I am missing the gradient lines. I have an idea on how to do it, need time to implement it.
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.patches import FancyBboxPatch
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 = { 2022 : "#A54836", 2004: "#5375D4", }
xy_ticklabel_color, label_color, grid_color, datalabels_color ='#757C85',"#101628", "#C8C9C9", "#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)
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 so we use pandas groupby and then sort the data.
df['sub_total'] = df.groupby('countries')['sites'].transform('sum')
df = df.sort_values([ 'countries'], ascending=False ).reset_index(drop=True)
df['year_lbl'] ="'"+df['year'].astype(str).str[-2:].astype(str)
df['pct_change'] = df.groupby('countries', sort=False)['sites'].apply(
lambda x: x.pct_change()).to_numpy()
#map the colors of a dict to a dataframe
df['color']= df.year.map(color_dict)
index | year | countries | sites | sub_total | year_lbl | pct_change | color |
---|---|---|---|---|---|---|---|
0 | 2004 | Sweden | 13 | 28 | ’04 | NaN | #5375D4 |
1 | 2022 | Sweden | 15 | 28 | ’22 | 0.153846 | #A54836 |
2 | 2004 | Norway | 5 | 13 | ’04 | NaN | #5375D4 |
3 | 2022 | Norway | 8 | 13 | ’22 | 0.600000 | #A54836 |
4 | 2004 | Denmark | 4 | 14 | ’04 | NaN | #5375D4 |
5 | 2022 | Denmark | 10 | 14 | ’22 | 1.500000 | #A54836 |
Create a function to draw lines with gradient
#function to color a line
def multiColorLine(xstart, xend, ystart, yend, npoints, line_thickness, colors, ax, ):
x = np.linspace(xstart, xend, npoints)
y = [ystart]*(int(npoints/3)) + np.linspace(ystart,yend,int(npoints/3)).tolist() + [yend]*int(npoints/3)
cmap = LinearSegmentedColormap.from_list("", colors)
norm = plt.Normalize(x.min(), x.max())
line_colors = cmap(norm(x))
ax.scatter(x, y, color=line_colors, s=line_thickness)
Define the variables
nr_countries = df.countries.nunique()
countries = df.countries.unique()
years = df.year.unique()
lbl = df.year_lbl.unique()
colors= df.color.unique()
img = [plt.imread("flags/sw-sq.png"),plt.imread("flags/no-sq.png"), plt.imread("flags/de-sq.png")]
Plot the chart
fig, axes = plt.subplots(ncols = nr_countries, nrows = 1, figsize=(8,5),sharex=True, sharey=True, facecolor = "#FFFFFF", zorder= 1)
fig.tight_layout(pad=1.0)
y2004 = df[df.year==2004]['sites']
y2022 = df[df.year==2022]['sites']
for country, im, y04,y022, ax in zip(countries, img, y2004,y2022, axes.ravel()):
temp_df = df[df.countries==country]
x = temp_df.year
y = temp_df.sites
pct = temp_df['pct_change'].max()
ax.bar(x, height = y, width=7,color = colors)
multiColorLine(2001, 2025, -0.5, -0.5, 900, 0.01, colors, ax)
multiColorLine(2001, 2025, y04+0.3, y022+0.3, 900, 0.01, colors, ax)
#add the grand totals at the top of the bars
for bar, site in zip(ax.patches, y):
ax.text(
bar.get_x() + bar.get_width() / 2,
round(bar.get_height())+0.5, #height
site, ha="center", va="bottom", size= 12,
color = label_color, weight= "bold", )
image_box = OffsetImage(im, zoom = 0.05) #container for the image
ab = AnnotationBbox(image_box, (2013,1), xybox= (2013, -4), frameon = False) # the x coordinate is the year axis
ax.add_artist(ab)
####
# Round the edges
# #######
new_patches = []
for patch in reversed(ax.patches):
# print(bb.xmin, bb.ymin,abs(bb.width), abs(bb.height))
bb = patch.get_bbox()
color = patch.get_facecolor()
p_bbox = FancyBboxPatch((bb.xmin, bb.ymin),
abs(bb.width), abs(bb.height),
boxstyle="round,pad=-0.0040,rounding_size=1",
ec="none", fc=color,
mutation_aspect=0.2
)
patch.remove()
new_patches.append(p_bbox)
for patch in new_patches:
ax.add_patch(patch)
#####
# end of round the edges
# #####
ax.spines[['right', 'bottom','top','left']].set_visible(False)
ax.set_ylim(-1,16)
ax.xaxis.set_ticks(years, labels =lbl, color= label_color)
ax.tick_params(axis='both', which='major',length=0, labelsize=11,colors= label_color)
ax.set_yticklabels([])
#add the symbol and pct labels
ax.annotate(f'\u25B2\n{pct:.1%}', xy= (.5, .2),size= 12, color= label_color, weight = "bold", va = "center", ha = "center", xycoords="axes fraction" )
ax.set_xlabel(country, size=14, color = label_color)
ax.xaxis.set_label_coords(0.5,-0.25)
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:

Reader Interactions