Connected scatterplot with Python

Cedric Vidonne

Lei Chen

Connected scatterplot with Python

A connected scatterplot is a type of visualization that displays the evolution of a series of data points that are connected by straight line segments. In some cases, it is not the most intuitive to read; but it is impressive for storytelling.

More about: Connected scatterplot


Connected scatterplot

# import libraries
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.ticker import MaxNLocator
plt.style.use(['unhcrpyplotstyle', 'connected_scatterplot'])

#load data set
df = pd.read_csv('https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/correlation/scatterplot_connected.csv')

#compute data array for plotting
x = df['refugee_number']
y = df['idp_number']
z = df['year']

#plot the chart
fig, ax = plt.subplots()
ax.plot(x, y, marker='o')

# Loop for annotation of all points
for i in range(len(x)):
    plt.annotate(z[i], (x[i], y[i]), textcoords="offset points", xytext=(3,3), ha='left')
    
limx = plt.xlim(2000000, 4000000)
limy = plt.ylim(0, 4000000)

#set chart title
ax.set_title('Evolution of refugee vs IDP population in Afghanistan | 2001-2021')

#set axis label
ax.set_xlabel('Number of refugees (millions)')
ax.set_ylabel('Number of IDPs (millions)')

#format axis tick labels
def number_formatter(x, pos):
    if x >= 1e6:
        s = '{:1.1f}M'.format(x*1e-6)
    elif x < 1e6 and x > 0:
        s = '{:1.1f}K'.format(x*1e-3)
    else: 
        s = '{:1.0f}'.format(x)
    return s
ax.xaxis.set_major_formatter(number_formatter)
ax.yaxis.set_major_formatter(number_formatter)
ax.xaxis.set_major_locator(MaxNLocator(4))
ax.yaxis.set_major_locator(MaxNLocator(4))

#set chart source and copyright
plt.annotate('Source: UNHCR Refugee Data Finder', (0,0), (0, -40), xycoords='axes fraction', textcoords='offset points', va='top', color = '#666666', fontsize=9)
plt.annotate('©UNHCR, The UN Refugee Agency', (0,0), (0, -50), xycoords='axes fraction', textcoords='offset points', va='top', color = '#666666', fontsize=9)

#adjust chart margin and layout
fig.tight_layout()

#show chart
plt.show()

A connected scatterplot showing evolution of refugee vs IDP population in Afghanistan | 2001-2021


Related chart with Python