#180 Basic lollipop plot

 

 

 

This page aims to explain the basic tricks allowing to realize a lollipop plot with matplotlib.

Here is a first example with 2 numerical variables, one for each axis.

A lollipop plot can be created 1: using the stem() function or 2: using the vline() function. The 3 methods proposed below create the same output!

 

 

 

 

 


# library
 import matplotlib.pyplot as plt
 import numpy as np

# create data
 x=range(1,41)
 values=np.random.uniform(size=40)

# stem function: first way
 plt.stem(x, values)
 plt.ylim(0, 1.2)
 #plt.show()

# stem function: If no X provided, a sequence of numbers is created by python:
 plt.stem(values)
 #plt.show()

# stem function: second way
 (markerline, stemlines, baseline) = plt.stem(x, values)
 plt.setp(baseline, visible=False)
 #plt.show()

 

 

Then, a lollipop plot works as well if you have one numerical and one categorical variable. In this case it is closer from a barplot. I highly recommend to order your groups, and I personally prefer to display this vertically. The stem function does not allow to make it vertically, so you will have to use the hline and the plot functions as follow.


# Create a dataframe
import pandas as pd
df = pd.DataFrame({'group':list(map(chr, range(65, 85))), 'values':np.random.uniform(size=20) })

# Reorder it following the values:
ordered_df = df.sort_values(by='values')
my_range=range(1,len(df.index)+1)

# Make the plot
plt.stem(ordered_df['values'])
plt.xticks( my_range, ordered_df['group'])


# Vertical version.
plt.hlines(y=my_range, xmin=0, xmax=ordered_df['values'], color='skyblue')
plt.plot(ordered_df['values'], my_range, "D")
plt.yticks(my_range, ordered_df['group'])
plt.show()

 

Don’t forget that you can easily improve the quality of your chart, simply loading the seaborn library before calling your matplotlib chart!


import seaborn as sns
plt.hlines(y=my_range, xmin=0, xmax=ordered_df['values'], color='skyblue')
plt.plot(ordered_df['values'], my_range, "D")
plt.yticks(my_range, ordered_df['group'])

 

Leave a Reply

Your email address will not be published.