Python 如何将参数传递给 animation.FuncAnimation()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37111571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass arguments to animation.FuncAnimation()?
提问by vinaykp
How to pass arguments to animation.FuncAnimation()
? I tried, but didn't work. The signature of animation.FuncAnimation()
is
如何将参数传递给animation.FuncAnimation()
? 我试过了,但没有奏效。的签名animation.FuncAnimation()
是
class matplotlib.animation.FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, **kwargs) Bases: matplotlib.animation.TimedAnimation
class matplotlib.animation.FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, **kwargs) 基础:matplotlib.animation.TimedAnimation
I have pasted my code below. Which changes I have to make?
我在下面粘贴了我的代码。我必须做出哪些改变?
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()
回答by Pedro Jorge De Los Santos
Check this simple example:
检查这个简单的例子:
# -*- 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()
First, for data handling is recommended to use NumPy, is simplest read and write data.
首先,对于数据处理推荐使用NumPy,是最简单的读写数据。
Isn't necessary that you use the "plot" function in each animation step, instead use the set_xdata
and set_ydata
methods for update data.
不必在每个动画步骤中使用“绘图”功能,而是使用set_xdata
和set_ydata
方法更新数据。
Also reviews examples of the Matplotlib documentation: http://matplotlib.org/1.4.1/examples/animation/.
还回顾了 Matplotlib 文档的示例:http://matplotlib.org/1.4.1/examples/animation/ 。
回答by Ed Smith
I think you're pretty much there, the following has a few minor tweaks basically you need to define a figure, use the axis handle and put fargs
inside a list,
我认为你已经差不多了,下面有一些小的调整,基本上你需要定义一个图形,使用轴手柄并放入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()
I replace example.txt
with a hardwired string as I didn't have the file and added in a dependency on i
so the plot moves.
我example.txt
用硬连线字符串替换,因为我没有文件并添加了依赖项,i
因此情节移动。
回答by Jeremie Gerhardt
Intro
介绍
Below you will find an example of code how to pass an argument properly to the animation.funcAnimationfunction.
您将在下面找到如何将参数正确传递给animation.funcAnimation函数的代码示例。
If you save all the code parts below as a single .pyfile you can call the script as follow in your terminal:
$python3 scriptLiveUpdateGraph.py -d data.csv
where data.csvis your data file containing data you want to display live.
如果将下面的所有代码部分保存为单个.py文件,则可以在终端中按如下方式调用脚本:
$python3 scriptLiveUpdateGraph.py -d data.csv
其中data.csv是包含要实时显示的数据的数据文件。
The usual modules import
常用模块导入
Below is my script starting:
下面是我的脚本开始:
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)
Some function
一些功能
Here I declare the function that will be called later by the animation.funcAnimationfunction.
这里我声明了以后会被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))
Process the input parameters
处理输入参数
To make the script more interactive I have added the possibility to read input file with argparse:
为了使脚本更具交互性,我添加了使用argparse读取输入文件的可能性:
parser = argparse.ArgumentParser()
parser.add_argument("-d","--data",
help="data path to the data to be displayed.",
type=str)
args = parser.parse_args()
Call the function to do the animation
调用函数做动画
And know we are answering the main question of this thread:
并且知道我们正在回答这个线程的主要问题:
ani = animation.FuncAnimation(fig, animate, fargs=(args.data,), interval=1000 )
plt.show()