python - plotting dynamic data using matplotlib -


i'm writing application display data changes dynamically (the data being read socket).

as dummy case, try draw sine amplitude multiplied 1.1 each second:

import numpy np import matplotlib.pyplot plt import time  x = np.arange(0, 10, 0.1); y = np.sin(x)   in xrange(100):     plt.plot(x, y)     time.sleep(1)     y=y*1.1 

this not way it, shows intentions.

how can done correctly?

edit: following traceback output of code suggested in @mskimm answer:

plt.show() #exception in thread thread-2: traceback (most recent call last):   file "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner     self.run()   file "/usr/lib/python2.7/threading.py", line 505, in run     self.__target(*self.__args, **self.__kwargs)   file "<ipython-input-5-ed773f8e3e84>", line 7, in update     plt.draw()   file "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 466, in draw     get_current_fig_manager().canvas.draw()   file "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 240, in draw     tkagg.blit(self._tkphoto, self.renderer._renderer, colormode=2)   file "/usr/lib/pymodules/python2.7/matplotlib/backends/tkagg.py", line 12, in blit     tk.call("pyaggimagephoto", photoimage, id(aggimage), colormode, id(bbox_array)) runtimeerror: main thread not in main loop 

edit 2:

it turns out same code works when run in qtconsole... (any idea why?) how ever, each print rescaling plot, "animation effect" missing. try use plt.autoscale_view(false,false,false) caused no plot @ all.

there better ways using matplotlib animation api, here's quick , dirty approach:

import numpy np import matplotlib.pyplot plt  x = np.arange(0, 10, 0.1) y = np.sin(x)  plt.ion() ax = plt.gca() ax.set_autoscale_on(true) line, = ax.plot(x, y)  in xrange(100):     line.set_ydata(y)     ax.relim()     ax.autoscale_view(true,true,true)     plt.draw()     y=y*1.1     plt.pause(0.1) 

the key steps are:

  1. turn on interactive mode plt.ion().
  2. keep track of line(s) want update, , overwrite data instead of calling plot again.
  3. give python time update plot window calling plt.pause.

i included code autoscale viewport, that's not strictly necessary.


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -