Print

64 of 100: Donut chart in 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!

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

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.

colors = [ "#CE5A43", "#5375D4",]

data = {
    "year": [2004, 2022, 2004, 2022, 2004, 2022],
    "countries" : ["Sweden", "Sweden", "Denmark", "Denmark", "Norway", "Norway"],
    "sites": [13,15,4,10,5,8]
}
indexyearcountriessites
02004Sweden13
12022Sweden15
22004Denmark4
32022Denmark10
42004Norway5
52022Norway8

We need to create the subtotals for each year so we use pandas groupby 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([ 'countries'], ascending=True ).reset_index(drop=True)

Load map data

map_df = gpd.read_file("https://raw.githubusercontent.com/eurostat/Nuts2json/master/pub/v2/2021/3035/20M/0.json")
map_df['country'] = map_df['id'].astype(str).str[:2]
map_df = map_df[map_df.country.isin(['NO','SE', 'DK']) ]

Define the variables

lat= [-100,-20,-50]
lon =[-120,-80,60]
x = len(df.year.unique())
countries = df.countries.unique()
totals = df.sub_total.unique()

xmin =[1,1,0]
xmax =[1.5,1.5,-0.5]

Plot the chart

fig = plt.figure(figsize=(15,14))
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,xmi,xma in zip(lat,lon,countries, totals,xmin,xmax):
    ax_pie = fig.add_axes([0.5*(1+ln/180) , 0.5*(1+lt/90) , 0.2, 0.4])  
    data = df[df["countries"] == country]
    years= data.year  

    patches, texts, autotexts  =  ax_pie.pie(data.sites, 
           autopct='%1.0f%%',
            pctdistance=0.75,
            wedgeprops=dict(width=0.45),    
        startangle=90,colors= colors)
    ax_pie.text(np.pi/2-1.6,0, total,va="center", ha="center", size= 32 )
    ax_pie.text(np.pi/2-1.6,-1.3, country,va="center", ha="center", size= 14 )
    ax_pie.axhline( y= 0, xmin =xmi, xmax=xma,lw=1, clip_on = False, color="#939AA1")

    [autotext.set_color('white') for autotext in autotexts]

The result:

64 of 100: Donut chart in a map in matplotlib
Was this helpful?

Reader Interactions

Leave a Reply

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

Table of Contents