0

I want to create something that can show (and hide with the same button) a line.

Here's what I have for the moment :

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button


fig, ax = plt.subplots()

class Index(object):
   ind = 0

   def test(self, event):
     self.plt.plot([0, 0], [1, 1])
     plt.draw()


callback = Index()
axtest = plt.axes([0.81, 0.05, 0.1, 0.075])
btest = Button(axtest, 'Test')
btest.on_clicked(callback.test)


plt.show()

Can someone help me with this script ? I really can't figure out how to do this.

nahusznaj
  • 463
  • 4
  • 15
SagemOg
  • 5
  • 5
  • I run your code and got an empty plot with a test button. I'm not sure what you get or what you want to achieve. Could you post an image of what you want or a better description? Sorry if it's evident. But see this https://stackoverflow.com/help/mcve – nahusznaj Jun 21 '18 at 13:29

1 Answers1

0

self.plt does not make sense. Apart, your scipt will always add a new plot. Instead you would maybe want to toggle the visibility (and possibly change the data) of an existing plot.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button


fig, ax = plt.subplots()

class Index(object):
    def __init__(self, line):
        self.line = line

    def test(self, event):
        if self.line.get_visible():
            self.line.set_visible(False)
        else:
            # possibly change data here, for now same data is used
            self.line.set_data([0,1],[0,1])
            self.line.set_visible(True)
            self.line.axes.relim()
            self.line.axes.autoscale_view()
        self.line.figure.canvas.draw()

line, = plt.plot([],[], visible=False)

callback = Index(line)
axtest = plt.axes([0.81, 0.05, 0.1, 0.075])
btest = Button(axtest, 'Test')
btest.on_clicked(callback.test)


plt.show()
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Can this be done over an image that has been displayed using `plt.imshow(img)`? – S_S Mar 15 '22 at 13:55