MatplotLib get all annotation by axes
Asked Answered
P

1

6

i'm doing a project with Python and Tkinter. I can plot an array of data and i also implemented a function to add annotation on plot when i click with the mouse, but now i need a list of all annotation that i added. Is there any way to have that? This is my function to add annotation:

def onclick(self, event):

    clicked = []
    key = event.key
    x = event.xdata
    y = event.ydata

    x_d = min(range(len(self.x_data)), key=lambda i: abs(self.x_data[i] - x))
    local_coord = self.x_data[x_d - 6:x_d + 6]
    x_1 = max(local_coord)
    indx = np.where(self.x_data == x_1)[0][0]
    y_1 = self.y_data[indx]



    if key == "v":
        self.ax.annotate("{0}nm".format(int(x_1)), size=25,
                         bbox=dict(boxstyle="round",fc="0.8"),
                         xy=(x_1, y_1), xycoords='data',
                         xytext=(x_1, y_1+50), textcoords='data',
                         arrowprops=dict(arrowstyle="-|>",
                                         connectionstyle="bar,fraction=0",
                                         ))

    self.canvas.draw()
Pollard answered 15/6, 2016 at 16:34 Comment(0)
K
15

You could loop over all the ax children and check if the child is of type matplotlib.text.Annotation:

for child in ax.get_children():
    if isinstance(child, matplotlib.text.Annotation):
        print("bingo") # and do something

Or, if you want a list:

annotations = [child for child in ax.get_children() if isinstance(child, matplotlib.text.Annotation)]
Kamilahkamillah answered 15/6, 2016 at 17:37 Comment(1)
Thanks you very much, it is what i was looking forPollard

© 2022 - 2024 — McMap. All rights reserved.