#182 Vertical lollipop plot

 

 

 

 

When a lollipop plot shows the relationship between a numerical and a categorical variable. I find it better to order the groups on a decreasing order and represent them vertically.

Here is how the code works, using a pandas data frame as input. Note that the stem function does not allow to realize vertical lollipop, thus you need to use the hline function.

 

 

 

 

 


# libraries
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# Create a dataframe
df = pd.DataFrame({'group':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)

# The vertival plot is made using the hline function
# I load the seaborn library only to benefit the nice looking feature
import seaborn as sns
plt.hlines(y=my_range, xmin=0, xmax=ordered_df['values'], color='skyblue')
plt.plot(ordered_df['values'], my_range, "o")

# Add titles and axis names
plt.yticks(my_range, ordered_df['group'])
plt.title("A vertical lolipop plot", loc='left')
plt.xlabel('Value of the variable')
plt.ylabel('Group')

 

 

Leave a Reply

Your email address will not be published.