在matplotlib中遇到FuncAnimantion函数的问题。代码如下:
import time
from matplotlib import pyplot as plt
from matplotlib import animation
from ppbase import *
plt.ion()
#This is just essentially a stream of data
Paramater = PbaProObject("address of object")
fig = plt.figure()
ax = plt.axes(xlim=(0,2), ylim=(-90, 90))
line, = ax.plot([], [], lw=2)
def init():
line.set_data([], [])
return line,
def animate(Parameter):
x = time.time()
y = Parameter.ValueStr
line.set_data(x, y)
return line,
anim = animation.FuncAnimation(fig, animate(Parameter), init_func=init,
frames=200, interval=2, blit=True)
plt.show()
错误是:
Traceback (most recent call last):
File "C:\Anaconda\lib\site-packages\matplotlib\backend_bases.py", line 1203, in _on_timer
ret = func(*args, **kwargs)
File "C:\Anaconda\lib\site-packages\matplotlib\animation.py", line 876, in _step
still_going = Animation._step(self, *args)
File "C:\Anaconda\lib\site-packages\matplotlib\animation.py", line 735, in _step self._draw_frame(framedata)
File "C:\Anaconda\lib\site-packages\matplotlib\animation.py", line 754, in _draw_next_frame self._draw_frame(framedata, self._blit)
File "C:\Anaconda\lib\site-packages\matplotlib\animation.py", line 1049, in _draw_frame self._drawn_artists = self._func(framedata, *self._args)
TypeError: 'tuple' object is not callable
整个上午都在阅读,看起来普通的plt.plot被一个元组覆盖了,所以我检查了一下,但是我觉得我没有在任何地方做过。我也把blit变成了假,但这也没有帮助。我也想以交互方式更新x轴,我有线: ax = plt.axes(xlim((x-10),(x + 10)),ylim =( - 90,90)) 在动画功能中,但是把它拿出来看它是否有所不同。
我认为问题主要来自于没有真正理解元组。我对FuncAnimation函数的理解是它每次更新绘图时调用animate() - 因此我也可以使用它来更新轴。但情况可能并非如此。
任何帮助表示感谢。
答案 0 :(得分:1)
您需要传入函数 object 而不是调用函数的结果,并且您可以将生成器传递给frames
(这可能仅适用于1.4.0+)。
# turn your Parameter object into a generator
def param_gen(p):
yield p.ValueStr
def animate(p):
# get the data the is currently on the graph
old_x = line.get_xdata()
old_y = line.get_ydata()
# add the new data to the end of the old data
x = np.r_[old_x, time.time()]
y = np.r_[old_y, p]
# update the data in the line
line.set_data(x, y)
# return the line2D object so the blitting code knows what to redraw
return line,
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=param_gen(Parameter), interval=2, blit=True)
我还解决了动画功能的问题,你应该使用4个空格缩进,而不是2个。