2

I'd like to be able to click on the two buttons generated in the IPython GUI and then generate a total of 6 points on the same graph. However, right now clicking the two buttons does not create the 6 points, and only creates the graph made by the first button to be clicked. What am I doing wrong?

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from ipywidgets.widgets import Button
from IPython.display import display

class Test(object):
    def __init__(self):
        self.figure = plt.figure()
        self.ax = self.figure.gca()
        self.button = Button(description = "Draw new points.")
        display(self.button)
        self.button.on_click(self.button_clicked)
        self.button2 = Button(description = "Draw more points.")
        display(self.button2)
        self.button2.on_click(self.button_clicked2)

    def button_clicked(self, event):
        self.ax.scatter([1,2,8], [6,5,4])
        self.figure.canvas.draw()
        plt.show()

    def button_clicked2(self, event):
        self.ax.scatter([1,0,5], [3,8,3])
        self.figure.canvas.draw()
        plt.show()

test = Test()
Alex
  • 3,946
  • 11
  • 38
  • 66

1 Answers1

1

I played around with your code and got it to work by adding %matplotlib notebook and removing calls to plt.show().

%matplotlib notebook
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from ipywidgets.widgets import Button
from IPython.display import display

class Test(object):
    def __init__(self):
        plt.ion()
        self.figure = plt.figure()
        self.ax = self.figure.gca()
        self.button = Button(description = "Draw new points.")
        display(self.button)
        self.button.on_click(self.button_clicked)
        self.button2 = Button(description = "Draw more points.")
        display(self.button2)
        self.button2.on_click(self.button_clicked2)

    def button_clicked(self, event):
        self.ax.scatter([1,2,8], [6,5,4])
        self.figure.canvas.draw()

    def button_clicked2(self, event):
        self.ax.scatter([1,0,5], [3,8,3])
        self.figure.canvas.draw()

test = Test()

Make sure that you have the latest version of matplotlib installed. This functionality depends on the nbagg backend. See this question for more information.

Community
  • 1
  • 1
bpachev
  • 2,162
  • 15
  • 17