2

Using iPython and matplotlib, I want to be able to add an annotation (or any object), remove it from the graph, and then re-add it. Essentially I want to toggle the appearance of the object in the graph.

Here is how I am adding and removing this object. The object still exists after the remove(). But I can't figure out how to make it reappear in the graph.

an = ax.annotate('TEST', xy=(x, y), xytext=(x + 15, y), arrowprops=dict(facecolor='#404040'))
draw() 
an.remove()
DJElbow
  • 3,345
  • 11
  • 41
  • 52

2 Answers2

2

You want set_visible (doc)

an = gca().annotate('TEST', xy=(.1, .1), xytext=(.1 + 15,.1), arrowprops=dict(facecolor='#404040'))
gca().set_xlim([0, 30])
draw() 
plt.pause(5)
an.set_visible(False)
draw()
plt.pause(5)
an.set_visible(True)
draw()
tacaswell
  • 84,579
  • 22
  • 210
  • 199
2

A snippet from an.remove() help goes: "The effect will not be visible until the figure is redrawn". If you do this:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure('A figure title')
ax = fig.add_subplot(111, autoscale_on=False, xlim=(-1,5), ylim=(-3,5))

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = ax.plot(t, s, lw=3, color='purple')

ann=ax.annotate('offset', xy=(1, 1),  xycoords='data',xytext=(-15, 10),     textcoords='offset points',arrowprops=dict(facecolor='black', shrink=0.05),horizontalalignment='right', verticalalignment='bottom')

It will draw a figure with an annotation. To remove it all you need to do is:

ann.remove()
fig.canvas.draw()

so all you're missing is redrawing the figure.

Aleksander Lidtke
  • 2,876
  • 4
  • 29
  • 41