Lollipop chart with Python

Cedric Vidonne

Lei Chen

Lollipop chart with Python

As a variant of the bar/column chart, the lollipop chart consists of lines and dots at the end to highlight the values. Like a bar chart, a lollipop chart is used to compare categorical data.

More about: Lollipop chart


Lollipop chart

# import libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
plt.style.use(['unhcrpyplotstyle','lollipop'])

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

#sort value by descending order
df.sort_values('displaced_number',inplace=True)

#compute data array for plotting
x = df.loc[:, 'country_origin'].values
y = df.loc[:, 'displaced_number'].values

#plot the chart
fig, ax = plt.subplots()
ax.hlines(y=x, xmin=0, xmax=y)
ax.plot(y, x, 'o')

#set x-axis limit
xlimt = plt.xlim(0,7*1e6)

#set chart title
ax.set_title('People displaced across borders by country of origin | 2020')

#set x-axis label
ax.set_xlabel('Displaced population (millions)')

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

#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 lollipop chart showing people displaced across borders by country of origin | 2020


Related chart with Python