在animation.FuncAnimation()中传递参数

vin*_*ykp 4 python wxpython matplotlib

如何将参数传递给animation()函数?,我试过但是工作.animation.FuncAnimation()的原型是

class matplotlib.animation.FuncAnimation(fig,func,frames = None,init_func = None,fargs = None,save_count = None,**kwargs)Bases: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()
Run Code Online (Sandbox Code Playgroud)

小智 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()
Run Code Online (Sandbox Code Playgroud)

首先,对于数据处理,建议使用NumPy,是最简单的读写数据.

您不必在每个动画步骤中使用"plot"功能,而是使用set_xdataset_ydata方法更新数据.

另请参阅Matplotlib文档的示例:http://matplotlib.org/1.4.1/examples/animation/ .


小智 5

介绍

下面您将找到如何将参数正确传递给animation.funcAnimation函数的代码示例。

如果将下面的所有代码部分保存为单个.py文件,您可以在终端中调用脚本,如下所示: $python3 scriptLiveUpdateGraph.py -d data.csv 其中data.csv是包含要实时显示的数据的数据文件。

常用模块导入

下面是我的脚本开始:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import argparse
import time
import os

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
Run Code Online (Sandbox Code Playgroud)

一些功能

这里我声明了animation.funcAnimation函数稍后将调用的函数。

def animate(i, pathToMeas):
    pullData = open(pathToMeas,'r').read()
    dataArray = pullData.split('\n')
    xar = []
    yar = []
    colunmNames = dataArray[0].split(',')
    # my data file had this structure:
    #col1, col2
    #100, 500
    #95, 488
    #90, 456
    #...
    # and this data file can be updated when the script is running
    for eachLine in dataArray[1:]:
        if len(eachLine) > 1:
           x, y = eachLine.split(',')
           xar.append(float(x))
           yar.append(float(y))

   # convert list to array
   xar = np.asarray(xar)
   yar = np.asarray(yar)

   # sort the data on the x, I do that for the problem I was trying to solve.
   index_sort_ = np.argsort(xar)
   xar = xar[index_sort_]
   yar = yar[index_sort_]

   ax1.clear()
   ax1.plot(xar, yar,'-+')
   ax1.set_xlim(0,np.max(xar))
   ax1.set_ylim(0,np.max(yar))
Run Code Online (Sandbox Code Playgroud)

处理输入参数

为了使脚本更具交互性,我添加了使用argparse读取输入文件的可能性:

parser = argparse.ArgumentParser()
parser.add_argument("-d","--data",
                help="data path to the data to be displayed.",
                type=str)

args = parser.parse_args()
Run Code Online (Sandbox Code Playgroud)

调用该函数做动画

并且知道我们正在回答该线程的主要问题:

ani = animation.FuncAnimation(fig, animate, fargs=(args.data,), interval=1000 )
plt.show()
Run Code Online (Sandbox Code Playgroud)