How to generate animations to make plots that update themselves

Let's begin by importing the necessary functions and use the Matplotlib Notebook interactive backend. We will also import the FuncAnimation method from Matplotlib.animation.

Start by making the standard basic sine plot. We have also added a function that changes the Y data by moving it over to the first argument. We will now use the func.animation method. As we call the func.animation method with the figure and our update method as the two arguments, we get a nice animation of the sine wave:

# Basic FuncAnimation
nums = np.arange(0,10,0.1)
sin, = plt.plot(nums, np.sin(nums))
def update(i):
sin.set_ydata(np.sin(nums+i))
FuncAnimation(plt.gcf(), update)

Following is the output of the preceding code:

If we set the title to the current value of that argument (plt.title (i)), we will see that it will iterate through some integers. By default, func.animation will pass subsequent integers to the argument, and so we will see the title updating itself sequentially in integer values. To specify our own values for the animation—let's say we don't want to use integers but drive the sine curve with values between 0 and 2 pi—we can pass the frames=frames argument:

Here, we can see that the sine wave is actually iterating through based on the values from this frames array. When we update the title, we can see that it's actually updating in values, in steps of 0.1, which are the steps of the NumPy array. We can also specify what the interval of the frames is. By default, the interval is set to 200, and the units for that is milliseconds. To update the animation so that it's twice as fast, we can switch it to 100 milliseconds, 50 milliseconds, or all the way down to 10 milliseconds. By doing this, we will see the output updating quite quickly.

Keep in mind that when we get to very high frame rates, the backend may have difficulty rendering this.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.242.92