如何将参数传递给animation.FuncAnimation()?

问题描述 投票:4回答:2

如何将参数传递给animation.FuncAnimation()?我试过了,但是没用。 animation.FuncAnimation()的签名为

class matplotlib.animation.FuncAnimation(fig,func,frames = None,init_func = None,fargs = None,save_count = None,** kwargs)基础:matplotlib.animation.TimedAnimation

我已经在下面粘贴了我的代码。我必须进行哪些更改?

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()
python matplotlib wxpython
2个回答
12
投票

检查此简单示例:

# -*- 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_xdataset_ydata方法来更新数据。

也查看Matplotlib文档的示例:http://matplotlib.org/1.4.1/examples/animation/


2
投票

[我认为您已经到了这里,以下基本上有一些小的调整,您基本上需要定义一个图形,使用轴手柄并将fargs放在列表中,

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

fig, ax1 = plt.subplots(1,1)

def animate(i,argu):
    print(i, argu)

    #graph_data = open('example.txt','r').read()
    graph_data = "1, 1 \n 2, 4 \n 3, 9 \n 4, 16 \n"
    lines = graph_data.split('\n')
    xs = []
    ys = []
    for line in lines:
        if len(line) > 1:
            x, y = line.split(',')
            xs.append(float(x))
            ys.append(float(y)+np.sin(2.*np.pi*i/10))
        ax1.clear()
        ax1.plot(xs, ys)
        plt.grid()

ani = animation.FuncAnimation(fig, animate, fargs=[5],interval = 100)
plt.show()

[我用硬连线的字符串替换了example.txt,因为我没有文件,并且添加了对i的依赖关系,所以图可以移动。

© www.soinside.com 2019 - 2024. All rights reserved.