Home > Software engineering >  Annotate points in Matplotlib
Annotate points in Matplotlib

Time:07-03

I want to annotate points on a plot using the coordinates in the list I5. But running into an error. The expected output is attached.

import numpy as np
import matplotlib.pyplot as plt

I5 = [[(0.5, -0.5), (1.5, -0.5)], [(0.5, -0.5), (0.5, -1.5)], [(1.5, -0.5), (1.5, -1.5)], [(0.5, -1.5), (1.5, -1.5)]]

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

N=3   #len(inv_r) 1
X = np.arange(0,N,1)
Y = -X

for i in range(len(I5)):
    plt.annotate(I5[0][i])

x_sorted = np.sort(X)
y_sorted = np.sort(Y)
ax.set_xticks(x_sorted)
ax.set_yticks(y_sorted)
ax.set_xlim(x_sorted[0], x_sorted[-1])
ax.set_ylim(y_sorted[0], y_sorted[-1])
ax.grid()
ax.set_aspect('equal', 'box')
plt.show()

The error is

in <module>
    plt.annotate(I5[0][i])

  File "C:\Users\USER\anaconda3\lib\site-packages\matplotlib\_api\deprecation.py", line 335, in wrapper
    return func(*args, **kwargs)

TypeError: annotate() missing 1 required positional argument: 'xy'

The expected output is

enter image description here

CodePudding user response:

import numpy as np
import matplotlib.pyplot as plt

I5 = [[(0.5, -0.5), (0.5, -0.5)], [(0.5, -1.5), (0.5, -1.5)], [(1.5, -0.5), (1.5, -0.5)], [(1.5, -1.5), (1.5, -1.5)]]

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

N=3   #len(inv_r) 1
X = np.arange(0,N,1)
Y = -X

for i in range(0,len(I5)):
    plt.annotate(I5[i][0],I5[i][1])

x_sorted = np.sort(X)
y_sorted = np.sort(Y)
ax.set_xticks(x_sorted)
ax.set_yticks(y_sorted)
ax.set_xlim(x_sorted[0], x_sorted[-1])
ax.set_ylim(y_sorted[0], y_sorted[-1])
ax.grid()
ax.set_aspect('equal', 'box')
plt.show()

In the I5 list the first tuple is the text u whant to plot and the second tuple isthe coordinates where u plot the text i dont know if u want to add point but if u want, u delete the firsts tuples to have only the coordinates tuple and then go plt.plot(cord_tuple0,cord_tuple1) plt.show() pls praise me im new to this, this is my first answer! cheers!

  • Related