Anyone learning Python or machine learning is definitely aware of the creation of charts using the matplotlib.pyplot module. In this article, we will see how to animate a sample chart and then save it as a gif file.
The matplotlib package has an animation module. Two classes of these modules will be required, FuncAnimation and PillowWriter.
- fig - The figure object
- func - The function to call at each frame
- frames - Source of data to be passed to the function
- init_func - A function used to draw a clear frame
%matplotlib notebook - magic command - will make our plots interactive within the notebook
To begin, we will initialize empty objects as shown below
- fig, ax = plt.subplots()
- x, ysin, ycos = [], [], []
- ln1, = plt.plot([], [], 'ro')
- ln2, = plt.plot([], [], 'm*')
Please note that the call to plt.plot([],[], 'ro') returns a tuple with one element. This is unpacked into a variable ln1. To unpack single item tuples, this convention is followed. If you print the type of ln1 and ln2, you will get a Line2D object.
Lets define the init and update functions as shown below:
- def init():
- ax.set_xlim(0, 2*np.pi)
- ax.set_ylim(-1, 1)
-
- def update(i):
- x.append(i)
- ysin.append(np.sin(i))
- ycos.append(np.cos(i))
- ln1.set_data(x, ysin)
- ln2.set_data(x, ycos)
As can be seen from code, in init function we set our x and y axis limits. In the update function, the arrays x, ysin and ycos are appended with respective values and functions.
A Line2D object has set_data function in which you can pass the x values and y values. Now it's time to call our main animation function.
- ani = FuncAnimation(fig, update, np.linspace(0, 2*np.pi, 64), init_func=init)
- plt.show()
For the value of frames, I am passing an iterable with 64 values between 0 and 6.28 and that it. Run the code and enjoy the animation.
Once you are happy with your animation, you can convert this to a gif by inserting the following command once before the plt.show()
Later you can comment them out.
- writer = PillowWriter(fps=25)
- ani.save("demo_sine.gif", writer=writer)
Here, fps is frames per second. I hope you enjoy creating more animated charts of different types.