Search code examples
pythonmatplotlibenumerate

Using enumerate to label points on a plot with a different letter for each point


I am trying to print each point with a label that says Point A/B/C/D (- depending on which point it is) and the coordinates of each point. At the moment, all the points have the same letter but I would like them to be individual to the point. I have tried other ways but none have worked.

no_points = 4
list_no_points = list(range(no_points))
xs = [1.0, 2.0, 3.0, 4.0]
ys = [1.0, 2.0, 3.0, 4.0]

plt.plot(xs, ys, linestyle = '--', marker = 'o', color = 'r')

for xy in zip(xs, ys):
    for x,i in enumerate(list_no_points):
        list_no_points[x] = string.ascii_uppercase[i]
    plt.annotate(f' Point ' + list_no_points[x] + ' (%.3f, %.3f)' % xy, xy=xy, textcoords='data')

plt.show()


Solution

  • You dont need the 2nd nested for, and your string line can be inserted directly into the annotation:

    import string
    import matplotlib.pyplot as plt
    
    no_points = 4
    list_no_points = list(range(no_points))
    xs = [1.0, 2.0, 3.0, 4.0]
    ys = [1.0, 2.0, 3.0, 4.0]
    plt.plot(xs, ys, linestyle = '--', marker = 'o', color = 'r')
    
    for i, xy in enumerate(zip(xs, ys)):
        plt.annotate(f' Point ' + string.ascii_uppercase[i] + ' (%.3f, %.3f)' % xy, xy=xy, textcoords='data')
    
    plt.show()
    

    enter image description here