4

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!

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
mcfly
  • 1,151
  • 4
  • 33
  • 55

2 Answers2

7

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)

tacaswell
  • 84,579
  • 22
  • 210
  • 199
  • but how do i determine the name of the object? That is what i seem to be having trouble with since it is created in another class (another "self" -- if that makes sense?) – mcfly Aug 31 '12 at 21:37
  • @mcfly I would recommend (re)reading http://docs.python.org/tutorial/classes.html . – tacaswell Sep 01 '12 at 04:32
1

You need to add it like an artist to delete it like an artist

arrow2 = matplotlib.text.Annotation("I love it",xy=(0.5,0.5),xycoords='data',arrowprops=dict(arrowstyle="-")) 
ax2.add_artist(arrow2) 
arrow2.remove() 
Tinmarino
  • 3,693
  • 24
  • 33