Search code examples
arraysmatplotlibnumberspoint

Display numbers instead of points using pyplot


I have a nx2 dimension array representing n points with their two coordinates x, y. Using pyplot, I would like to display the number n of my points instead of just the points with no way to know which is what.

I have found a way to legend my points but really what I would like is only the number.

How can I achieve this ?


Solution

  • You may use plt.text to place the number as text in the plot. To have the number appear at the exact position of the coordinates, you may center align the text using ha="center", va="center".

    import numpy as np; np.random.seed(2)
    import matplotlib.pyplot as plt
    
    xy = np.random.rand(10,2)
    
    plt.figure()
    for i, ((x,y),) in enumerate(zip(xy)):
        plt.text(x,y,i, ha="center", va="center")
    
    plt.show()
    

    enter image description here

    In order to have the plot autoscale to the range where the values are, you may add an invisible scatter plot

    x,y =zip(*xy)
    plt.scatter(x,y, alpha=0) 
    

    or, if numbers are really small, better an invisible plot

    x,y =zip(*xy)
    plt.plot(x,y, alpha=0.0)