Open In App

Matplotlib.animation.FuncAnimation class in Python

Last Updated : 06 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
 

matplotlib.animation.FuncAnimation

The matplotlib.animation.FuncAnimation class is used to make animation by repeatedly calling the same function (ie, func).
 

Syntax: class matplotlib.animation.FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True, **kwargs)
Paramwrite.geeksforgeeks.org/wp-admin/post.php?post=1675187&action=editors: 
 

  1. fig: It is the figure object used for drawing, resizing or any other needed events. 
    Any additional positional arguments can be supplied via the fargs parameter.
     
  2. func: It is the callable function that gets called each time. The next value in frames is given through the first argument. Any other additional positional arguments is given via the fargs parameter. If the blit value is equal to True then, func returns an iterable of all artists that are to be modified or created. This data is used by the blitting algorithm to decide which parts of the figure has to be updated. If blit== False then the value returned is unused or omitted.
     
  3. frames: It is either an iterable, an integer, a generator function or None. It is an optional argument. It is the data source to be passed to func and every frame of the animation.
     
  4. init_func: It is an optional callable function that is used to draw a clear frame.
     
  5. fargs: It is an optional parameter that is either a tuple or None, which is an additional arguments that needs to be passed to each call to func.
     
  6. save_count: It is an integer that acts as fallback for the number of values from frames to cache. This is only used if the number of frames cannot be inferred from frames, i.e. when it’s an iterator without length or a generator.Its default is 100.
     
  7. interval: It is an optional integer value that represents the delay between each frame in milliseconds. Its default is 100.
     
  8. repeat_delay: It is an optional integer value that adds a delay in milliseconds before repeating the animation. It defaults to None.
     
  9. blit: It is an optional boolean argument used to control blitting to optimize drawing.
     
  10. cache_frame_data: It is an optional boolean argument used to control caching of data. It defaults to True. 
     

 

Methods of the class:
 

Methods Description
__init__(self, fig, func[, frames, …]) Initialize self.
new_frame_seq(self) Return a new sequence of frame information.
new_saved_frame_seq(self) Return a new sequence of saved/cached frame information.
save(self, filename[, writer, fps, dpi, …]) Save the animation as a movie file by drawing every frame.
to_html5_video(self[, embed_limit]) Convert the animation to an HTML5 <video> tag.
to_jshtml(self[, fps, embed_frames, …]) Generate HTML representation of the animation

Example 1: 
 

Python3




import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np
 
 
# creating a blank window
# for the animation
fig = plt.figure()
axis = plt.axes(xlim =(-50, 50),
                ylim =(-50, 50))
 
line, = axis.plot([], [], lw = 2)
 
# what will our line dataset
# contain?
def init():
    line.set_data([], [])
    return line,
 
# initializing empty values
# for x and y co-ordinates
xdata, ydata = [], []
 
# animation function
def animate(i):
    # t is a parameter which varies
    # with the frame number
    t = 0.1 * i
     
    # x, y values to be plotted
    x = t * np.sin(t)
    y = t * np.cos(t)
     
    # appending values to the previously
    # empty x and y data holders
    xdata.append(x)
    ydata.append(y)
    line.set_data(xdata, ydata)
     
    return line,
 
# calling the animation function    
anim = animation.FuncAnimation(fig, animate,
                            init_func = init,
                            frames = 500,
                            interval = 20,
                            blit = True)
 
# saves the animation in our desktop
anim.save('growingCoil.mp4', writer = 'ffmpeg', fps = 30)


Output: 
 

Example 2: 
 

Python3




from matplotlib import pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
 
# initializing a figure in
# which the graph will be plotted
fig = plt.figure()
 
# marking the x-axis and y-axis
axis = plt.axes(xlim =(0, 4),
                ylim =(-2, 2))
 
# initializing a line variable
line, = axis.plot([], [], lw = 3)
 
# data which the line will
# contain (x, y)
def init():
    line.set_data([], [])
    return line,
 
def animate(i):
    x = np.linspace(0, 4, 1000)
 
    # plots a sine graph
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
     
    return line,
 
anim = FuncAnimation(fig, animate,
                    init_func = init,
                    frames = 200,
                    interval = 20,
                    blit = True)
 
anim.save('continuousSineWave.mp4',
          writer = 'ffmpeg', fps = 30)


Output: 
 

 



Similar Reads

MoviePy – Creating Animation Using Matplotlib
In this article we will see how we create animations in MoviePy using matplotlib. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Video is formed by the frames, combination of frames creates a video each frame is an individual image. Matplotlib is a plotting library for the Python programmin
3 min read
How to save Matplotlib Animation?
In this article, we will learn How to save Matplotlib Animation. The animated graphs made with the help of matplotlib can be saved as videos in Python. As we can create captivating animations using the matplotlib library. If you want to learn to create animations, here is a link to the article to create animations using the matplotlib. In this arti
2 min read
Python | Create simple animation for console-based application
As we know Python is a scripting language, and can be easily used to automate simple tasks. In this article, we will learn how to create a simple console-based animation, which can be used while developing a console based project as a utility. We will try to replicate the loading animation as shown below: We will be using following modules - sys mo
2 min read
Python | Animation in Kivy using .kv file
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, Linux, and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. Animation: Animation and AnimationTransition are used to animate Widget properties. You must specify at least a
3 min read
Create a simple Animation using Turtle in Python
Turtle is a Python feature like a drawing board, which lets us command a turtle to draw all over it! We can use functions like turtle.forward(…) and turtle.right(…) which can move the turtle around. Let's create a basic animation where different little turtles race around a track created for them. Prerequisites: Turtle Programming in Python Require
4 min read
Creating a radar sweep animation using arcade in Python
The Radar Sweep are used for displays of single level sweeps of radar data, and their display appears in the Main Display window. With the help of arcade module of Python, it is possible to perform a radar sweep animation. Before starting, it is highly recommended to revise concepts of arcade library. To perform a radar sweep animation, follow the
3 min read
Python | Animation in Kivy
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. ?? Kivy Tutorial - Learn Kivy with Examples.Animation: Animation and AnimationTransition are used to animate Widg
2 min read
Violinplot in Python using axes class of Matplotlib
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. #Sample Code # Implementation of matplotlib functi
2 min read
Matplotlib.ticker.MultipleLocator Class in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. matplotlib.ticker.MultipleLocator The matplotlib.ticker.MultipleLocator class is used for setting a tick for every integer multiple of a b
1 min read
Matplotlib.gridspec.GridSpec Class in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. matplotlib.gridspec.GridSpec The matplotlib.gridspec.GridSpec class is used to specify the geometry of the grid to place a subplot. For th
3 min read