For matplotlib in python,
There is a function that can flexibly create animation. How to use this function.
sample_animation.py
import matplotlib.animation as anm
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize = (10, 6))
x = np.arange(0, 10, 0.1)
def update(i, fig_title, A):
if i != 0:
plt.cla() #Erase the currently depicted graph
y = A * np.sin(x - i)
plt.plot(x, y, "r")
plt.title(fig_title + 'i=' + str(i))
ani = anm.FuncAnimation(fig, update, fargs = ('Initial Animation! ', 2.0), \
interval = 100, frames = 132)
ani.save("Sample.gif", writer = 'imagemagick')
If you execute the above code, the following animation file "Sample.gif" should be generated.
The key is
ani = anm.FuncAnimation(fig, update, fargs = ('Initial Animation! ', 2.0), \
interval = 100, frames = 132)
A sentence.
figure object. Give commands related to figures (animation) to this object.
A callback function that creates each of the figures that make up the animation.
Creating an animation means creating multiple diagrams and stitching them together, but with the `` `FuncAnimationfunction, you can call it multiple times by calling the function that creates the diagram. It has been realized.
update```The rules of the function are as follows.
--Define before the FuncAnimation
function.
--Make sure that the figure is initialized when this function is called the second time or later.
--The `plt.cla ()`
part of the above sample program corresponds to it.
--This function has at least one argument.
--The first argument of this function (i
in the above sample program) is an integer that increments from 0 to 1 each time this function is called.
--If you want to have two or more arguments to this function, specify it with `` `fargs``` (described later).
An option that allows you to specify the second and subsequent arguments when you want to provide two or more arguments to the update
function of the second argument.
In the example of the above sample program, `" Initial Animation! "``` Is in the second argument
fig_title``` of the ```update``` function, and the third argument ```A
. 2.0
is passed to `` respectively.
You can specify the time interval at which the figure changes in the animation (in milliseconds).
interval = 100
Then, "the figure changes once every 100 milliseconds".
Specify the number of times to call the update function.
frames = 132
Thenupdate
The function is called 132 times, and the generated gif animation is a combination of 132 still images.
(The first argument of the update
function, i
, takes the value 0,1, ..., 131 in the meantime)
Recommended Posts