import pandas as pd
import matplotlib.pyplot as plt

%matplotlib inline

How to create lollipop charts from a pandas dataframe

Read in your data

df = pd.read_csv("../street-data.csv")
df.head()
street shootings duration dur_per_day dur_per_hour
0 Java Str 161 2547.0 1.163014 0.048459
1 East 18 Str 170 2547.0 1.163014 0.048459
2 Grand Str 168 2619.0 1.195890 0.049829
3 Eagle Str 180 2626.0 1.199087 0.049962
4 10 Av 159 2638.0 1.204566 0.050190

The inflexible way: using plt.stem

After I wrote this rest of this, I read about plt.stem. It makes everything so easy! But it’s kiiiind of inflexible, which is why you might want to try the other options.

fig, ax = plt.subplots()

# Draw the stem and circle
ax.stem(df.street, df.dur_per_day, basefmt=' ')

# Start the graph at 0
ax.set_ylim(0, 1.5)
(0, 1.5)

png

Building a horizontal lollipop graph with a categorical y axis

We’re going to use plot.subplots() to make an empty graph, then…

  • ax.hlines is going to draw horizontal lines. This takes an xmin and an xmax.
  • ax.plot is going to draw circles (like a scatterplot)
  • ax.set_xlim to make the graph start at 0

Not so bad!

fig, ax = plt.subplots()

ax.hlines(df.street, xmin=0, xmax=df.dur_per_day)
ax.plot(df.dur_per_day, df.street, "o", color='black')
ax.set_xlim(0, 1.5)
(0, 1.5)

png

Building a verticla lollipop graph with a categorical x axis

It’s basically the same as before, but all of the horizontal lines become vertical, and our axes are switched on our scatterplot. We’re going to use plot.subplots() to make an empty graph, then…

  • ax.vlines is going to draw vertical lines. This takes a ymin and a ymax.
  • ax.plot is going to draw circles (like a scatterplot)
  • ax.set_ylim to make the graph start at 0

Just as easy!

fig, ax = plt.subplots()

ax.vlines(df.street, ymin=0, ymax=df.dur_per_day)
ax.plot(df.street, df.dur_per_day, "o", color='black')
ax.set_ylim(0, 1.5)
(0, 1.5)

png