#!/usr/bin/env python

import matplotlib
matplotlib.use('WXAgg')
import numpy as np

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanvas
import wx
import time

# A flag to pause between every command in the update stage
slowdown=False
#--------------------------------------------------------------------------------------
class MainFrame(wx.Frame,matplotlib.figure.Figure):
    """Main frame for a simple graph."""
    def __init__(self, parent, id):
        wx.Frame.__init__(self,None,-1)

        # creating the matplotlib figure and canvas.
        self._fig = matplotlib.figure.Figure( None)
        self.canvas = FigCanvas(self, wx.ID_ANY, self._fig )

        self.canvas.mpl_connect('draw_event', self.savebg)
        # creating some data
        self.x = np.arange(0,2*np.pi,0.01)


        # adding the suplot and a line.
        self.ax = self._fig.add_subplot(111)
        self.line, = self.ax.plot(self.x, np.sin(self.x), animated=True)
        if slowdown==True:
            time.sleep(1)

        # Update when there is idle time. Note that this will only refire when
        # something happens (such as a mouse movement) this will allow
        # a better view of the dynamics of the updates.
        self.Bind(wx.EVT_IDLE, self.update_line)

        # a variable to induce change
        self.update_line_cnt=0

        self.canvas.draw()

        return

    def savebg(self, *args):
        # save the clean slate background -- everything but the animated line
        # is drawn and saved in the pixel buffer background

        self.background = self._fig.canvas.copy_from_bbox(self.ax.bbox)


    #--------------------------------------------------------------------------------------
    def update_line(self,event):
        """ This function will update and redraw the data"""

        # update the data
        self.line.set_ydata(np.sin(self.x+self.update_line_cnt/20.0))

        # restore the clean slate background
        self._fig.canvas.restore_region(self.background)
        if slowdown==True:
            time.sleep(1)

        # just draw the animated artist
        self.ax.draw_artist(self.line)
        if slowdown==True:
            time.sleep(1)

        # just redraw the axes rectangle
        self._fig.canvas.blit(self.ax.bbox)
        if slowdown==True:
            time.sleep(1)

        # Uncomment to speed up updates without actions.
        #event.RequestMore(True)

        #Getting some changes
        self.update_line_cnt+=1

        return True

#--------------------------------------------------------------------------------------
if __name__ == '__main__':


    App=wx.App()
    frame=MainFrame(None,-1)
    frame.Show(True)

    App.MainLoop()






