Getting graph to update when I move the slider

Hi,

I’m trying to plot a simple graph using wxpython and matplotlib, and have it update when I move the slider. The code below draws the graph initially, but it is not updated when I move the slider. Would be grateful for some help.

Thanks :slight_smile:

from math import pi
from numpy import arange, sin, pi
import matplotlib
matplotlib.use('WXAgg')
from matplotlib.figure import Figure
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg as NavigationToolbar2Wx
import wx

class MyCanvasPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.val = 0
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()
        self.slider = wx.Slider(self, value=0, minValue=0, maxValue=1000, style = wx.SL_HORIZONTAL)
        self.slider.Bind(wx.EVT_SLIDER, self.OnSliderScroll)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
        sizer.Add(self.slider, 0, wx.LEFT | wx.EXPAND)
        self.SetSizer(sizer)
        self.Fit()

    def OnSliderScroll(self, e):
        self.val = e.GetEventObject().GetValue() * 0.001 * 2 * pi
        self.Draw()  # this does not update the graph...

    def Draw(self):
        t = arange(0.0, 1.0, 0.01)
        s = sin(self.val * t)
        self.axes.plot(t, s)

class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, size=(620, 620))
        self.SetMinSize((620, 620))
        self.panel = MyCanvasPanel(self)
        self.panel.Draw()

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame()
        self.SetTopWindow(frame)
        frame.Show(True)
        return True

def main():
    app = MyApp(False)
    app.MainLoop()

if __name__ == "__main__" :
    main()

Try:

    def Draw(self):
        t = arange(0.0, 1.0, 0.01)
        s = sin(self.val * t)
        self.axes.clear()
        self.axes.plot(t, s)
        self.canvas.draw()

However, It doesn’t quite work because it resets the scaling of the axes, but it does draw the graph.

Alternatively:

    def Draw(self):
        t = arange(0.0, 1.0, 0.01)
        s = sin(self.val * t)
        self.axes.clear()
        self.axes.set_xlim(0,1)
        self.axes.set_ylim(-1,1)
        self.axes.plot(t, s)
        self.canvas.draw()

Excellent. Thank you!