Guest User

animation_example

a guest
May 11th, 2016
231
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # -*- coding: utf-8 -*-
  2. import matplotlib
  3. matplotlib.use('wxAgg')
  4. from matplotlib.figure import Figure
  5. import matplotlib.animation as animation
  6. from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
  7.  
  8. import wx
  9. import numpy as np
  10.  
  11. class Frame(wx.Frame):
  12.     def __init__(self,*args,**kwargs):
  13.         wx.Frame.__init__(self,*args,**kwargs)
  14.         self.initCtrls()
  15.         self.Centre(True)
  16.         self.Show()
  17.        
  18.     def initCtrls(self):
  19.         self.mainsz = wx.BoxSizer(wx.HORIZONTAL)
  20.         self.figure = Figure()
  21.         self.axes = self.figure.add_subplot(111)
  22.         self.canvas = FigureCanvas(self, wx.ID_ANY, self.figure)
  23.        
  24.         # Combo-Box
  25.         self.options = wx.ComboBox(self, wx.ID_ANY, choices=["Anim 01","Anim 02"])
  26.        
  27.         self.mainsz.Add(self.options, 1, wx.ALIGN_LEFT)
  28.         self.mainsz.Add(self.canvas, 4, wx.EXPAND)
  29.         self.SetSizer(self.mainsz)
  30.        
  31.         # Bind
  32.         self.Bind(wx.EVT_COMBOBOX, self.OnSelect, self.options)
  33.        
  34.         # Plot line
  35.         self.line, = self.axes.plot([],[], '-')
  36.         self.anim = None
  37.        
  38.     def OnSelect(self,event):
  39.         if event.GetSelection()==0:
  40.             self.initAnim_01()
  41.         elif event.GetSelection()==1:
  42.             self.initAnim_02()
  43.        
  44.     def initAnim_01(self):
  45.         data = np.loadtxt("example1.txt", delimiter=",")
  46.         self.x = data[:,0]
  47.         self.y = data[:,1]
  48.         self._initAnim()
  49.        
  50.     def initAnim_02(self):
  51.         data = np.loadtxt("example2.txt", delimiter=",")
  52.         self.x = data[:,0]
  53.         self.y = data[:,1]
  54.         self._initAnim()
  55.    
  56.     def _initAnim(self):
  57.         if not self.anim is None:
  58.             # Stop previous animation
  59.             self.anim._stop()
  60.         self.axes.set_xlim(np.min(self.x), np.max(self.x))
  61.         self.axes.set_ylim(np.min(self.y), np.max(self.y))
  62.         self.anim = animation.FuncAnimation(self.figure, self.animate, frames=len(self.x),
  63.                                       interval=50, blit=True)
  64.         self.canvas.draw()
  65.         self.Layout() # Update
  66.        
  67.     def animate(self,i):
  68.         self.line.set_xdata(self.x[:i])
  69.         self.line.set_ydata(self.y[:i])
  70.         return self.line,
  71.  
  72.  
  73. if __name__ == "__main__":
  74.     app = wx.App()
  75.     fr = Frame(None, wx.ID_ANY, "Example", size=(600,400))
  76.     app.MainLoop()
RAW Paste Data