如何将参数传递给 animation.FuncAnimation()
?我试过了,但没有奏效。 animation.FuncAnimation()
的签名是
我在下面粘贴了我的代码。我必须做出哪些改变?
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def animate(i,argu):
print argu
graph_data = open('example.txt','r').read()
lines = graph_data.split('\n')
xs = []
ys = []
for line in lines:
if len(line) > 1:
x, y = line.split(',')
xs.append(x)
ys.append(y)
ax1.clear()
ax1.plot(xs, ys)
plt.grid()
ani = animation.FuncAnimation(fig,animate,fargs = 5,interval = 100)
plt.show()
最佳答案
检查这个简单的例子:
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
data = np.loadtxt("example.txt", delimiter=",")
x = data[:,0]
y = data[:,1]
fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot([],[], '-')
line2, = ax.plot([],[],'--')
ax.set_xlim(np.min(x), np.max(x))
ax.set_ylim(np.min(y), np.max(y))
def animate(i,factor):
line.set_xdata(x[:i])
line.set_ydata(y[:i])
line2.set_xdata(x[:i])
line2.set_ydata(factor*y[:i])
return line,line2
K = 0.75 # any factor
ani = animation.FuncAnimation(fig, animate, frames=len(x), fargs=(K,),
interval=100, blit=True)
plt.show()
首先,对于数据处理推荐使用NumPy,是最简单的读写数据。
不必在每个动画步骤中使用“绘图”功能,而是使用
set_xdata
和 set_ydata
方法更新数据。还回顾了 Matplotlib 文档的示例: http://matplotlib.org/1.4.1/examples/animation/ 。
关于python - 如何将参数传递给 animation.FuncAnimation()?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37111571/