Skip to content
Advertisement

How to draw a line between a data point and an axis in matplotlib?

Using matplotlib one can use:

  • plt.hlines/vlines to draw segments (e.g. between two data points)
  • plt.axhline/axvline to draw lines relative to the axes

My question is: what is the simplest way to do half of each? Typically, drawing a segment from a datapoint to its coordinate on the x or y axis.

Advertisement

Answer

In my opinion, this is simple enough (4 lines):

fig, ax = plt.subplots()
x = np.arange(10)
y = np.arange(10)
ax.plot(x, y)
# starting from here
ymin, ymax = ax.get_ylim()
for i in range(len(x)):
    ax.vlines(x[i], ymin, y[i])
ax.set_ylim(ymin, ymax)

Output:

enter image description here

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement