import matplotlib.pyplot as plt
plt.ion()
class DynamicUpdate():
#Suppose we know the x range
min_x = 0
max_x = 10
def on_launch(self):
#Set up plot
self.figure, self.ax = plt.subplots()
self.lines, = self.ax.plot([],[], 'o')
#Autoscale on unknown axis and known lims on the other
self.ax.set_autoscaley_on(True)
self.ax.set_xlim(self.min_x, self.max_x)
#Other stuff
self.ax.grid()
...
def on_running(self, xdata, ydata):
#Update data (with the new _and_ the old points)
self.lines.set_xdata(xdata)
self.lines.set_ydata(ydata)
#Need both of these in order to rescale
self.ax.relim()
self.ax.autoscale_view()
#We need to draw *and* flush
self.figure.canvas.draw()
self.figure.canvas.flush_events()
#Example
def __call__(self):
import numpy as np
import time
self.on_launch()
xdata = []
ydata = []
for x in np.arange(0,10,0.5):
xdata.append(x)
ydata.append(np.exp(-x**2)+10*np.exp(-(x-7)**2))
self.on_running(xdata, ydata)
time.sleep(1)
return xdata, ydata
d = DynamicUpdate()
d()
import joystick as jk
import numpy as np
import time
class test(jk.Joystick):
# initialize the infinite loop decorator
_infinite_loop = jk.deco_infinite_loop()
def _init(self, *args, **kwargs):
"""
Function called at initialization, see the doc
"""
self._t0 = time.time() # initialize time
self.xdata = np.array([self._t0]) # time x-axis
self.ydata = np.array([0.0]) # fake data y-axis
# create a graph frame
self.mygraph = self.add_frame(jk.Graph(name="test", size=(500, 500), pos=(50, 50), fmt="go-", xnpts=10000, xnptsmax=10000, xylim=(None, None, 0, 1)))
@_infinite_loop(wait_time=0.2)
def _generate_data(self): # function looped every 0.2 second to read or produce data
"""
Loop starting with the simulation start, getting data and
pushing it to the graph every 0.2 seconds
"""
# concatenate data on the time x-axis
self.xdata = jk.core.add_datapoint(self.xdata, time.time(), xnptsmax=self.mygraph.xnptsmax)
# concatenate data on the fake data y-axis
self.ydata = jk.core.add_datapoint(self.ydata, np.random.random(), xnptsmax=self.mygraph.xnptsmax)
self.mygraph.set_xydata(t, self.ydata)
t = test()
t.start()
t.stop()
在matplotlib中,有多种设置数据动画的方法,具体取决于您拥有的版本。你看过这些例子吗?另外,请查看matplotlib文档中更现代的animation examples。最后,animation API定义了一个函数FuncAnimation,它可以及时地为函数设置动画。这个函数可能只是用来获取数据的函数。
每个方法基本上都设置要绘制的对象的
data
属性,因此不需要清除屏幕或图形。可以简单地扩展data
属性,这样您就可以保留前面的点,并继续添加到您的线(或图像或您正在绘制的任何内容)中。假设您说您的数据到达时间不确定,那么您最好的选择可能是执行以下操作:
然后,当您从串行端口接收数据时,只需调用
update_line
。为了在不使用FuncAnimation的情况下执行此操作(例如,您希望在生成绘图时执行代码的其他部分,或者希望同时更新多个绘图),仅调用
draw
不会生成绘图(至少在qt后端)。以下对我有效:
我知道我来不及回答这个问题,但对于你的问题,你可以看看“操纵杆”包。我设计它是为了绘制来自串行端口的数据流,但它适用于任何流。它还允许交互式文本记录或图像打印(除了图形打印)。 不需要在单独的线程中执行自己的循环,包会处理它,只需给出您希望的更新频率。此外,终端在打印时仍可用于监视命令。 请参阅http://www.github.com/ceyzeriat/joystick/或https://pypi.python.org/pypi/joystick(使用pip安装操纵杆进行安装)
只要用从串行端口读取的实际数据点替换np.random.random(),代码如下:
相关问题 更多 >
编程相关推荐