Home > Software engineering >  How to draw a line between a data point and an axis in matplotlib?
How to draw a line between a data point and an axis in matplotlib?

Time:09-28

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.

CodePudding user response:

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

  • Related