Print

7 of 100: Scatter plot 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

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, xy_label_colors, grid_color,  ='#9BA0A6',"#9BA0A6", "#C8C9C9", 

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

Define the variables:

#define x and y axis
country = df.countries.unique()
colors = df.color.unique()
sites_max = df.sites.max()
year_max = df.year.max()
year_min = df.year.min()

x = df[df.year == year_max]["sites"].values
y = df[df.year == year_min]["sites"].values

Plot the scatter chart

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

#set the color and the position of the axis guidelines/spines
for axis in ['top', 'bottom', 'left', 'right']:
    ax.spines[axis].set_color(grid_color) 
    ax.spines[axis].set_zorder(0)

#change grid color
ax.grid(True,  color = grid_color)

#create the scatter (white and colored one)
ax.scatter(x, y,clip_on=False, s= 100, zorder=2,color = colors )
ax.scatter(x, y,clip_on=False, s= 1, zorder=2, color = "w")

#hide ticks + other
ax.tick_params(axis='both', which='major',length=0, labelsize=12,colors =xy_ticklabel_color)


# Change x-axis tick spacing
ax.set(xlim=(0, sites_max), ylim=(0,sites_max))
ax.xaxis.set_ticks(np.arange(0, 20, 5))
ax.yaxis.set_ticks(np.arange(0, 20, 5))

#add axis titles
ax.set_xlabel(year_max, size = 12, color = xy_label_colors, weight = "bold")
ax.set_ylabel(year_min, size=12, color = xy_label_colors, weight= "bold")


#scatter labels
for x,y, ctry,c  in zip(x,y, country, colors):
    ax.annotate(ctry, xy = (x, y), xytext=(x, y+3),
                va='center', ha="center",
            color='w', weight= "bold",
        bbox=dict(ec =c, boxstyle='round,pad=0.5', fc = c),
         arrowprops=dict( arrowstyle='-',color = c ,) )
    ax.text( x,y+2.3,"\u25BC", size= 12, ha="center", va="center", color = c)

The result:

7 of 100: Scatter plot in matplotlib
Was this helpful?

Reader Interactions

Leave a Reply

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

Table of Contents