Plotting in Python | Set 3

File handling | NumPy | Python Methods and Functions

Matplotlib — quite extensive library that also supports animation charts. The animation tools are centered around the base class matplotlib.animation , which provides the foundation upon which the animation functionality is built. The main interfaces are TimedAnimation and FuncAnimation and of the the most convenient to use is FuncAnimation .

Setting :

  • Matplotlib : refer to graphical plotting in Python | Bundle 1
  • Numpy: You can install the numpy module using the following pip command:
     pip install numpy 
  • FFMPEG : only required to save animation as video. The executable can be downloaded here .

Implementation:

# import required modules

import matplotlib.pyplot as plt

import matplotlib.animation as animation

import numpy as np

 
# create shape, axis and plot element

fig = plt.figure ()

ax = plt.axes (xlim = ( - 50 , 50 ), ylim = ( - 50 , 50 ))

line, = ax.plot ( [], [], lw = 2 )

 
# init function

def init ():

# create empty graphic / frame

  line.set_data ([], [] )

r eturn line,

 
# lists to store x and y points

xdata, ydata = [], []

 
# function animations

def animate (i):

# t is a parameter

t = 0.1 * i

 

# x, y values ​​to build

x = < / code> t * np.sin (t)

y = t * np.cos (t)

 

  # add new points to the x, y points list

xdata.append (x)

  ydata.append (y)

  

# set / update X and Y axis data

line.set_data (xdata, ydata)

  

  # return string

  return line,

 
# setting the title for the plot

plt.title ( `A growing coil!` )

# hide axis details

plt.axis ( ` off` )

  
# call animator

anim = animation.FuncAnimation (fig, animate, init_func = init,

  frames = 500 , interval = 20 , blit = True )

 
# save animation as MP4 video file

anim.save ( `animated_coil.mp4` , writer = `ffmpeg` , fps = 30 )

 
# show plot
plt.show ()

This is what the output animation looks like:

Now let`s try to understand the code piece by piece:

  •  fig = plt.figure () ax = plt.axes (xlim = (- 50, 50), ylim = (- 50, 50)) line, = ax.plot ([], [], lw = 2) 

    Here we first create a shape, that is, a top-level container for all our parcels. 
    Then we create an axes ax, element that acts as a subplot. The range / limit for the x and y axes is also determined when the axis element is created. 
    Finally, we create a story element named line . Originally the x and y axis points were defined as empty lists, and the line width (lw) was set to 2.

  •  def init (): line .set_data ([], []) return line, 

    Now we declare the initialization function init . This function is called by the animator to create the first frame.

  •  def animate (i): # t is a parameter t = 0.1 * i # x, y values ​​to be plotted x = t * np.sin (t) y = t * np.cos (t) # appending new points to x, y axes points list xdata.append (x) ydata.append (y) # set / update the x and y axes data line.set_data (xdata, ydata) # return line object return line, 

    This is the most important function of the above program. The animate () function is called by the animator over and over to create each frame. The number of calls to this function is determined by the number of frames passed as an argument to frames to the animator. 
    The animate () function takes the index of the i-th frame as an argument.

     t = 0.1 * i 

    Here we cleverly use the index of the current frame as a parameter!

     x = t * np.sin (t) y = t * np.cos (t) 

    Now, since we have a t parameter , we can easily construct any parametric equation. For example, here we are plotting a spiral using its parametric equation.

     line.set_data (xdata, ydata) return line, 

    Finally, we use the set_data () function to set the x and y data, and then return the plot object, line .

  •  anim = animation.FuncAnimation (fig, animate, init_func = init, frames = 500, interval = 20, blit = True) 

    Now we create a FuncAnimation object, anim . This takes various arguments, explained below:
    pic : The drawing to build. 
    animate : a function that will be called again for each frame.
    init_func : a function used to draw a clean border ... Called once before the first frame. 
    frames : number of frames. (Note: frames can also be iterables or generators.)
    spacing : duration between frames (in milliseconds)
    blit : setting blit = True means that only the parts that have changed will be drawn.

  •  anim.save (`animated_coil.mp4`, writer =` ffmpeg`, fps = 30) 

    Now we save the animator object as a video file using the save () function. You will need a movie maker to save your animated video. In this example, we used the FFMPEG Movie Writer. So writer is set to & # 39; ffmpeg & # 39 ;. 
    fps stands for frames per second.

Example 2

This example shows how you can make a rotating curve using simple math!

# import of required modules

import matplotlib.pyplot as plt

import matplotlib.animation as animation

import numpy as np

 
# create shape, axis and plot element

fig = plt.figure ()

ax = plt.axes (xlim = ( - 25 , 25 ), ylim = ( - 25 , 25 ))

line, = ax.plot ([], [], lw = 2 )

 
# init function

def init ():

# create empty chart / frame

line.set_data ([], [])

  return line,

  
# a set of points for a star (can be any curve)

p = np.arange ( 0 , 4 * np.pi, 0.1 )

x = 12 * np.cos (p ) + 8 * np.cos ( 1.5 * p)

y = 12 * np.sin (p) - 8 * np.sin ( 1.5 * p)

 
# animation function

def animate (i):

# t is a parameter

t = 0.1 * i

  

# x, y values ​​to build

X = x * np.cos ( t) - y * np.sin (t)

  Y = y * np.cos (t) + x * np.sin (t)

 

# set / update X and Y axis data

line .set_data (X, Y)

 

  # return string

  return line,

  
# setting a title for the story

plt.title ( `A rotating star!` )

# hide axis details

plt.axis ( `off` )

 
# call animator

anim = animation.FuncAnimation (fig, animate, init_func = init,

frames = 100 , interval =   100 , blit = True )

 
# save animation as MP4 video file

anim.save ( `basic_animation.mp4` , writer = `ffmpeg` , fps = 10 )

 
# show plot
plt.show ()

This is how the result of the above program looks like:

Here we used some simple math to get just rotate this curve.

  • The star shape is obtained by putting k = 2.5 and 0 & lt; t & lt; 4 * pi in the parametric equation below:

    The same was applied here:

     p = np.arange (0, 4 * np.pi, 0.1) x = 12 * np.cos (p) + 8 * np.cos (1.5 * p) y = 12 * np.sin (p) - 8 * np.sin (1.5 * p) 
  • Now in each frame we rotate the curve of the star, using the concept of rotation in complex numbers. Let x, y be two ordinates. Then, after turning theta angle, new ordinates:

    The same was applied here:

     X = x * np.cos (t) - y * np.sin (t) Y = y * np.cos (t) + x * np.sin (t) 

In general, animation — it is a great tool for creating amazing things, and with them you can create even more things.

So this is how you can create and save animated plots with Matplotlib.

This article is provided by by Nikhil Kumar . If you like Python.Engineering and would like to contribute, you can also write an article using contrib.python.engineering, or email your article to [email protected] See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.





Get Solution for free from DataCamp guru