1

I have a plot with a time series and one or several axvspan lines to highlight some areas and to extract the time series value and instant but I would like to have the possibility to delete one or all those axvspan lines with a button. I have looked some examples on how to delete lines (How can I delete plot lines that are created with Mouse Over Event in Matplolib?) but I can´t find nothing related with axvspan lines. This is the code that I'm using to create the axvspan line(s)

    def on_click(event):
        global x0
        x0 = event.xdata

    def on_release(event):
        global force_values
        if force_value == "Min":
            self.axes.axvspan(x0,event.xdata, facecolor='y', alpha=0.5)
            get_data(frames,force_values,x0,event.xdata)
        else:
            self.axes.axvspan(x0,event.xdata, facecolor='r', alpha=0.5)
            get_data(frames,force_values,x0,event.xdata)

Thanks in advance for your help. Kind Regards Ivo

Community
  • 1
  • 1
TMoover
  • 620
  • 1
  • 7
  • 22

1 Answers1

6

Almost all artist objects have a remove member function which will remove them from axes:

aspan = self.axes.axvspan(x0,event.xdata, facecolor='y', alpha=0.5)
# do stuff
aspan.remove()
plt.draw()

If you need to do a bunch of them, then you just need to keep track of a bunch of them

self.aspan_list = []
self.aspan_list.append(self.axes.axvspan(x0,event.xdata, facecolor='y', alpha=0.5))
#...
for aspan in self.aspan_list:
    aspan.remove()
tacaswell
  • 84,579
  • 22
  • 210
  • 199
  • I wasn't assigning the axvspan to a variable so I was getting an error saying that axvspan doesn´t has that method (remove). Now I can finally delete the last axvspan that I create in my plot. Since I need to draw several axvspan in the same plot, and I would like to know if there is a way to delete all at once? I used the same code but when I press the delete axvspan button several times it will delete just the last axvspan and leave the others. Thank you for your help. Kind Regards. Ivo – TMoover Nov 05 '13 at 15:28