Joshhh Joshhh - 8 days ago 5
Python Question

Vertical lines to points in scatter plot

Suppose I have a set of points

x
and a set of corresponding data
y
. I now plot these in a scatter plot,
plt.scatter(x,y)
. The figure I get contains some x axis tick generated by matplotlib. Is there a way I can attain the automatic ticking, but to add vertical lines from the x-axis to the point in the scatter and label them?

Answer

Like this?

altered scattergram

If so then here are the essentials.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import collections as matcoll

x = np.arange(1,13)
y = [15,14,15,18,21,25,27,26,24,20,18,16]

lines = []
for i in range(len(x)):
    pair=[(x[i],0), (x[i], y[i])]
    lines.append(pair)

linecoll = matcoll.LineCollection(lines)
fig, ax = plt.subplots()
ax.add_collection(linecoll)

plt.scatter(x,y)

plt.xticks(x)
plt.ylim(0,30)

plt.show()