Search code examples
pythonmatplotlibplotscatter-plot

plot coordinates line in a pyplot


I have a scatter plot. I would like to plot coordinate lines for each point, from X to Y, just like we used to do on school.

See picture below as a reference.

enter image description here

I ended up using the "grid()" property, but that is not exactly what I want.

I also tried to use "axhline" and "axvline" passing xmin, xmax and ymin, ymax, but it did not work. It crossed a line throughout the entire plot.

Have a great day!


Solution

  • You can use vlines to draw the vertical lines and hlines to draw the horizontal lines. These are different from axvline and axhline, since those functions take values between 0 and 1 while vlines and hlines work in the data coordinates. I pass vlines the y.min() as ymin so it doesn't go too low and I pass hlines the x.min() as xmin so it doesn't go too far to the left. I also adjusted the zorder of the scatter plot so the lines are behind the points.

    import numpy as np
    import matplotlib.pyplot as plt
    
    plt.close("all")
    
    rng = np.random.default_rng(42)
    x = np.arange(2009, 2024)
    y = rng.random(x.size)*13
    
    fig, ax = plt.subplots()
    ax.scatter(x, y, zorder=3)
    ax.vlines(x, y.min(), y, color="r", linewidth=0.5)
    ax.hlines(y, x.min(), x, color="r", linewidth=0.5)
    fig.show()