Print

68 of 100: Clustered scatter 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: I havent found a good way to jitter and pack the bubbles, this is the closer I got.

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 ='#929EA7',"#101628", "#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

We need to sort the data and colors.

#custom sort
sort_order_dict = {"Denmark":2, "Sweden":1, "Norway":3}
df = df.sort_values(by=['countries',], key=lambda x: x.map(sort_order_dict))
#map the colors of a dict to a dataframe
df['color']= df.countries.map(color_dict)
yearcountriessitescolor
42004Sweden13#5375D4
52022Sweden15#5375D4
02004Denmark4#A54836
12022Denmark10#A54836
22004Norway5#2B314D
32022Norway8#2B314D

Define the variables

years = df.year
countries = df.countries.unique()
sites = df.sites
colors = df.color

Plot the chart

fig, axes = plt.subplots(ncols= 2, nrows = 3, figsize=(5,5),facecolor = "#FFFFFF")
fig.tight_layout(h_pad=1.0) #distance between plots
 
for ax,site, color in zip(axes.ravel(), sites, colors):
    #jitter: https://stackoverflow.com/questions/8671808/avoiding-overlapping-datapoints-in-a-scatter-dot-beeswarm-plot
    data = np.random.randn(site)

    width = 0.8     # the maximum width of each 'row' in the scatter plot
    xpos = 0        # the centre position of the scatter plot in x

    counts, edges = np.histogram(data, bins=4)

    centres = (edges[:-1] + edges[1:]) / 2.
    yvals = centres.repeat(counts)

    max_offset = width / counts.max()
    offsets = np.hstack([(np.arange(cc) - 0.5 * (cc - 1)) for cc in counts])
    xvals = xpos + (offsets * max_offset)
    ax.scatter(xvals, yvals, s=40,  c = color)

    ax.set(xlim=(-0.5,0.5), ylim = (-3,4))
    ax.spines[['left','top', 'bottom', 'right']].set_visible(False)
    ax.tick_params(axis='both', which='major', length=0, )
    ax.set_yticklabels([])
    ax.set_xticklabels([])

   
for ax, year in zip(axes[:,0], countries):
    ax.set_ylabel(year, rotation=0,size= 12,color = xy_ticklabel_color)
    ax.yaxis.set_label_coords(-0.8, 0.5)

for ax, col in zip(axes[0], years):
    ax.set_title(col, x=0.5, y=1.2,color = xy_ticklabel_color) 

The result:

68 of 100: Clustered scatter 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