matplotlib is a python graph drawing module that can also create animations. In other words, it is a good idea for older brothers who die if they don't watch anime at midnight to learn matplotlib.
So, as a very simple sample, write code that just describes the random numbers generated by numpy.
Click here for the official documentation. http://matplotlib.org/api/animation_api.html
ArtistAnimation
There are two types of matplotlib animations: ArtistAnimation and FuncAnimation. ArtistAnimation prepares all the graphs in the form of an array in advance, and flows them one by one.
artistanimation.py
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
ims = []
for i in range(10):
rand = np.random.randn(100) #Generate 100 random numbers
im = plt.plot(rand) #Graph random numbers
ims.append(im) #Add graph to array ims
#Display 10 plots every 100ms
ani = animation.ArtistAnimation(fig, ims, interval=100)
plt.show()
It was quite like a radio wave. If you want to watch anime after working overtime late at night, it's a good idea to watch this kind of thing. When saving a video as a GIF, at the end
plt.show()
Part of
ani.save("output.gif", writer="imagemagick")
It is good to rewrite to. (Requires a package called imagemagick) It seems that it can output to MP4, but I haven't done it because it's a little troublesome.
FuncAnimation
This does not pass the pre-finished graph, but executes the function for each frame of the animation. Useful if the data is too large or potentially infinite.
funcanimation.py
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
def plot(data):
plt.cla() #Erase the currently depicted graph
rand = np.random.randn(100) #Generate 100 random numbers
im = plt.plot(rand) #Generate graph
ani = animation.FuncAnimation(fig, plot, interval=100)
plt.show()
Since this dynamically creates a graph, the range on the vertical axis changes each time according to the random numbers.
When outputting to GIF, unlike Artist Animation, the end is not specified, so
ani = animation.FuncAnimation(fig, plot, interval=100, frames=10)
ani.save("output.gif", writer="imagemagick")
Specify the number of frames in advance as frames = 10
.
Recommended Posts