Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python and Remove annotation from figure

I am using matplotlib inside of a wxpython GUI. In short, I have plotted a bunch of data. I then click on a data point (using DataCursor found at:

Is there a matplotlib equivalent of MATLAB's datacursormode?

or

Pop up annotations on matplotlib within wxPython

The second link is my actual implementation. I refrense the datacursor class from other classes. What i'm wondering, how do i remove the annotation by clicking an event button? For instance, I have an event button that updates my scatter plot (by using plot_handle.set_data and not by clearing the figure). However, the annotation remains exactly where it was regardless if the point is there or not. How do i remove it?

Thanks!

like image 896
mcfly Avatar asked Feb 19 '23 08:02

mcfly


1 Answers

Most matplotlib objects have a remove() function (I think it is inherited from Artist). Just call that on the object you want to remove.

Edit:

If you have

dc = DataCursor(...) # what ever aruguements you give it
# bunch of code
dc.annotation.remove()
del dc
plt.draw() # need to redraw to make remove visible

Python has no notion of 'private' attributes, so you can just reach inside you object and call remove on the annotation. See tutorial on classes for more details.

The down side of this is that now you have an object is a strange state. If you have any other references to it, they might behave badly. If you want to keep the DataCursor object around you can modify the annotation object using it's set_* functions or change it's visibility to temporarily hide it (doc)

like image 125
tacaswell Avatar answered Feb 22 '23 03:02

tacaswell