How to pass arguments to animation.FuncAnimation()?

40,313

Solution 1

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.

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.

Also reviews examples of the Matplotlib documentation: http://matplotlib.org/1.4.1/examples/animation/.

Solution 2

Intro

Below you will find an example of code how to pass an argument properly to the animation.funcAnimation function.

If you save all the code parts below as a single .py file you can call the script as follow in your terminal: $python3 scriptLiveUpdateGraph.py -d data.csv where data.csv is your data file containing data you want to display live.

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.funcAnimation function.

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:

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()

Solution 3

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,

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.

Share:
40,313
vinaykp
Author by

vinaykp

Updated on July 09, 2022

Comments

  • vinaykp
    vinaykp almost 2 years

    How to pass arguments to animation.FuncAnimation()? I tried, but didn't work. The signature of animation.FuncAnimation() is

    class matplotlib.animation.FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, **kwargs) Bases: 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()
    
  • vinaykp
    vinaykp almost 8 years
    thank you Jorge for wonderful answer. But set_xdata and set_ydata methods not working if we embed canvas in wxpython form. do you have any idea ?
  • Pedro Jorge De Los Santos
    Pedro Jorge De Los Santos almost 8 years
    Check this mini-adaptation using the wxPython backend, which is similar to the last example: http://pastebin.com/c1WSRRD7
  • vinaykp
    vinaykp almost 8 years
    thanks . I have done the same thing like ur implementation, but I have triggered the animate() when a option selected from the Drop down list. So when a option selected form the Drop down list animate() function was executed repeatedly for every given time.But nothing was displayed on the screen. Do you have any idea why that happens?
  • Pedro Jorge De Los Santos
    Pedro Jorge De Los Santos almost 8 years
    Check this example, using a ComboBox as animation selector: http://pastebin.com/7v4h6VzD
  • vinaykp
    vinaykp almost 8 years
    wow thats great , I was not setting the xlim and ylim . Is that necessary?
  • Pedro Jorge De Los Santos
    Pedro Jorge De Los Santos almost 8 years
    No, isn't strictly necessary, instead you can use relim() and autoscale_view() methods to adjust limit to current data.
  • vinaykp
    vinaykp almost 8 years
    I have tried with those relim() and autoscale_view() they dint work. Now I just commented relim() in your code and checked its not showing graph
  • vinaykp
    vinaykp almost 8 years
  • Pedro Jorge De Los Santos
    Pedro Jorge De Los Santos almost 8 years
    Where are placing these methods?.. relim() and autoscale_view() must be placed in animate method, just after set_xdata and set_ydata.
  • vinaykp
    vinaykp almost 8 years
    yes, I hv placed just after set_xdata and set_ydata