Print

46 of 100: Dot plot 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!

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
import matplotlib as mpl
from matplotlib.lines import Line2D
from svgpathtools import svg2paths
from svgpath2mpl import parse_path

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: "#CC5A43", 2004: "#5375D4", }

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)
indexyearcountriessites
02004Sweden13
12022Sweden15
22004Denmark4
32022Denmark10
42004Norway5
52022Norway8

We need to create the subtotals for each year, the difference in sites between the years 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')
#custom sort
sort_order_dict = {"Denmark":2, "Sweden":3, "Norway":1, 2004:5, 2022:4}
df = df.sort_values(by=['countries','year',], key=lambda x: x.map(sort_order_dict))
df['color']= df.year.map(color_dict)
yearcountriessitesdiffsub_totalcolor
52022Norway838#CC5A43
42004Norway558#5375D4
32022Denmark10610#CC5A43
22004Denmark4410#5375D4
12022Sweden15215#CC5A43
02004Sweden131315#5375D4

Generate the heritage icon

icon_path, attributes = svg2paths('flags/Unesco_World_Heritage_logo_notext_transparent.svg')
#matplotlib path object of the icon
icon_marker  = parse_path(attributes[0]['d'])

icon_marker.vertices -= icon_marker.vertices.mean(axis=0)
icon_marker = icon_marker.transformed(mpl.transforms.Affine2D().rotate_deg(180))
icon_marker = icon_marker.transformed(mpl.transforms.Affine2D().scale(-1,1))

Get the 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= [0.32,0.22,0.68]
lon =[0.5,0.14,0.28]
x = len(df.year.unique())
countries = df.countries.unique()
totals = df.sub_total.unique()
years = df.year.unique()

#create the matrix
X= np.repeat(np.arange(1,6),3)
Y = np.tile(np.arange(1,4),5)


xmin =[1,1,0]
xmax =[2,2.5,-1]

Plot the chart

for lt,ln,country,  total, xmi,xma in zip(lat,lon,countries, totals,xmin,xmax):
    ax_matrix= fig.add_axes([lt ,ln , 0.1, 0.2])  

    #add the colors for the symbol
    diff= df[df.countries==country]['diff']
    colors= df[df.countries==country]['color']
    symbol_color = np.insert(np.repeat(colors,diff).to_numpy(), 0,  ["#FFFFFF"]*(15-total))

    ax_matrix.scatter(Y,X, marker=icon_marker, s=800, color= symbol_color)
    ax_matrix.set_xlim(0,4)
    ax_matrix.set_ylim(0,6)
    ax_matrix.set_xlabel(f'{country} {total}', color=xy_ticklabel_color, size = 14)
    ax_matrix.set_yticklabels([])
    ax_matrix.set_xticklabels([])
    ax_matrix.grid(False)
    ax_matrix.set_frame_on(False)
    ax_matrix.tick_params(axis='both', which='both',length = 0)
    ax_matrix.axhline( y= -0.4, xmin =xmi, xmax=xma,lw=1, clip_on = False, color="#939AA1")


#add legend
text_legends = ["Before", "After"]
colors = ["#5475D6","r",]
lines = [Line2D([0], [0], color=c,  marker=icon_marker,linestyle='', markersize=20,) for c in colors]
labels  = [f'{text_legend} 2004' for  text_legend in text_legends]
for year in years:
    plt.figlegend( lines,labels,   
                  labelcolor=xy_ticklabel_color,
            bbox_to_anchor=(0.5, -0.05), loc="lower center",
                ncols = 2,frameon=False, fontsize= 12)
    

The result:

46 of 100: Dot plot on 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