Print

17 of 100: Bump 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: Automate the chart limits and ticks.

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

Import the 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", }

xy_ticklabel_color,  grid_color, datalabels_color ='#757C85', "#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)
Indexyearcountriessites
02004Sweden13
12022Sweden15
22004Denmark4
32022Denmark10
42004Norway5
52022Norway8

Then we need to add the rank and sort:

df = df.sort_values(['year','sites'  ], ascending=False ).reset_index(drop=True)
df["rank"] = df.groupby("year")["sites"].rank().astype(int)
#map the colors of a dict to a dataframe
df['color']= df.countries.map(color_dict)
indexyearcountriessitesrankcolor
02022Sweden153#5375D4
12022Denmark102#A54836
22022Norway81#2B314D
32004Sweden133#5375D4
42004Norway52#2B314D
52004Denmark41#A54836

Define the variables

unique_countries = df.countries.unique()
countries = df.countries
sites = df.sites
x = df.year
y = df['rank']
colors = df.color.unique()

Plot the chart

unique_countries = df.countries.unique()
countries = df.countries
sites = df.sites
x = df.year
y = df['rank']
colors = df.color.unique()


fig, ax = plt.subplots(figsize=(4,5), facecolor = "#FFFFFF")

for color, country in zip(colors,unique_countries):
    temp_df= df[df.countries ==country]
    ax.plot(temp_df.year, temp_df['rank'], '-o', markersize = 28, mec = "w", mew=4, color = color, zorder=1)
    # Get any single marker radius
    marker_radius = np.sqrt(ax.lines[0].get_markersize() / np.pi)
    

for i, site in enumerate(sites):
    ax.annotate(site, (x[i], y[i]), ha= "center", va="center", color= datalabels_color)

#add country legend at the end bar only 
offset_text = df['year'].max() + marker_radius * 1.4
for y, country, color in zip(range(1,4), reversed(countries[:3]), reversed(colors)):
    ax.annotate(country, (offset_text, y), ha= "left", va="center", color= color, annotation_clip=False)


ax.yaxis.set_ticks(np.arange(1, len(unique_countries)+1, 1))
ax.tick_params(axis='both', which='major',labeltop=True,labelbottom=False,length=0,labelsize=16,  colors= xy_ticklabel_color)

ax.spines[['top','bottom','left','right']].set_visible(False)
ax.xaxis.set_ticks(x, labels =x)

#draws in the data coordinates hlines
ax.hlines(np.linspace(0.5, len(unique_countries)+.5, num=len(unique_countries)+1), 1995, 2034, lw=0.5, color=grid_color, clip_on=False , zorder =0)

The result:

17 of 100: Bump chart in matplotlib
Was this helpful?

Reader Interactions

Comments

  1. Based on the current “To be improved: Automate the chart limits and ticks.”

    1. Remove the set_xlims() and set_ylims()

    2. Get any single marker radius (at line 6):
    marker_radius = np.sqrt(ax.lines[0].get_markersize() / np.pi)

    3. Change the offset_text variable:
    offset_text = df[‘year’].max() + marker_radius * 1.1
    Here, I am keeping 10% of the marker as space

    4. Set horizontal alignment to left (at line 13) and remove 2022:
    ax.annotate(country, (offset_text, y), ha= “left”, va=”center”, color= color, annotation_clip=False)

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents