Print

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

Left to do: I need to curve the text legends.

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
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, 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)

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 year labels and then sort the data.

df = df.sort_values([ 'sites'], ascending=True ).reset_index(drop=True)
df['year_lbl'] ="'"+df['year'].astype(str).str[-2:].astype(str)
#map the colors of a dict to a dataframe
df['color']= df.countries.map(color_dict)
yearcountriessitesyear_lblcolor
02004Denmark4’04#A54836
12004Norway5’04#2B314D
22022Norway8’22#2B314D
32022Denmark10’22#A54836
42004Sweden13’04#5375D4
52022Sweden15’22#5375D4

Define the variables

First we split the semi arc into 20 bars, offset it by 2 and we will have a bar height of 0.5

nr_bars = 20
bar_height = 0.5 #height of the bars
offset = 2 # offset of the bars

Then we define the angles for the bars and find what the angles are for each site (rad_x[df.site]) and define the location of the bubbles and arcs. Once we defined everything, we will add it to the dataframe so we slice it based on country.

#divide 180 degrees into 20 bars
rad_x = np.deg2rad(np.linspace(0,180,nr_bars, endpoint= False))
#add the angle for each site to the dataframe
df['angles'] = rad_x[df.sites]
#get the radius for each circle
r= [2+bar_height/3,2+bar_height/3*2,2+bar_height/3*2,2+bar_height/3,2+bar_height/2,2+bar_height/2]
#add the radius to the dataframe
df['radius'] = r
yearcountriessitesyear_lblcoloranglesradius
02004Denmark4’04#A548360.6283192.166667
12004Norway5’04#2B314D0.7853982.333333
22022Norway8’22#2B314D1.2566372.333333
32022Denmark10’22#A548361.5707962.166667
42004Sweden13’04#5375D42.0420352.250000
52022Sweden15’22#5375D42.3561942.250000

Next, we define the rest of the variables, the connection style for the arcs, as well as defining the axis labels and slice the angles and radius by country so we can then place the arcs using them.

year_labels= df.year_lbl
colors = df.color
legend = df.countries
theta = df.angles
radius = df.radius
sites = df.sites

#arch for the arrows
connectionstyle = ["arc3,rad=0.24","arc3,rad=0.15","arc3,rad=0.15"]

#slice angles and radius by country
angles_bycountry = df.groupby('countries')['angles'].apply(lambda x: x.values) 
r_bycountry = df.groupby('countries')['radius'].apply(lambda x: x.values)

#add axis labels
axis_labels = list(range(0,25,5))
theta_labels = np.array([rad_x[i] for i in list(range(0,20,5))])
label_pos = np.append(theta_labels,np.pi) #add the last coordinate of the label

Plot the chart

With everything in place it is time to plot the chart:

fig, ax = plt.subplots(figsize=(10, 7), subplot_kw=dict(polar=True))

ax.set_theta_zero_location("W")  # theta=0 at the top
ax.set_theta_direction(-1)  # theta increasing clockwise
ax.set_thetamax(180) # stop at 180 degrees


ax.bar(rad_x, width=np.deg2rad(180/nr_bars), height=bar_height,  bottom=offset,
       linewidth=1, edgecolor="white",color=grid_color,
        align="edge")
ax.scatter(theta, radius, color=colors, s = 305, zorder=2)

#add arcs
for angle,r, color,connectionstyle in zip(angles_bycountry,r_bycountry, colors.unique(),connectionstyle):
        ax.annotate("", xy=(angle[0],r[0]), xytext=(angle[1],r[1]), zorder = 1,
                arrowprops=dict(arrowstyle='-', connectionstyle = connectionstyle, 
                        color = color, alpha= 0.5, linewidth=2, linestyle='-', antialiased=True))

  
#bubble data labels
for t, r,lb in zip(theta, radius, year_labels):
    ax.annotate(lb, xy=(t,r), color ="w", size= 8, weight= "bold", ha="center", va="center")

# axis labels
for loc, val, r in zip( label_pos, axis_labels, radius):
    ax.annotate(val, xy=(loc, offset-0.2), size= 12, va= 'center', ha= 'center', color=xy_ticklabel_color)
    
ax.text(0.5, 0, "World Heritage \nSites", size=12, ha="center", va="center")

ax.set_axis_off()

The result:

2 of 100: Gauge 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