How To Make Animated Plots Python

How To Make Animated Plots Python

Matplotlib version 1.1 added some tools for creating animations which are really slick. You can find some good example animations on the matplotlib examples page. I thought I'd share here some of the things I've learned when playing around with these tools.

Here we create a figure window, create a single axis in the figure, and then create our line object which will be modified in the animation. Note that here we simply plot an empty line: we'll add data to the line later.

How

Is the function which will be called to create the base frame upon which the animation takes place. Here we use just a simple function which sets the line data to nothing. It is important that this function return the line object, because this tells the animator which objects on the plot to update after each frame:

Celluloid · Pypi

Note that again here we return a tuple of the plot objects which have been modified. This tells the animation framework what parts of the plot should be animated.

This object needs to persist, so it must be assigned to a variable. We've chosen a 100 frame animation with a 20ms delay between frames. The

Keyword is an important one: this tells the animation to only re-draw the pieces of the plot which have changed. The time saved with

Improving Time Series Animations In Matplotlib (from 2d To 3d)

One of the examples provided on the matplotlib example page is an animation of a double pendulum. This example operates by precomputing the pendulum position over 10 seconds, and then animating the results. I saw this and wondered if python would be fast enough to compute the dynamics on the fly. It turns out it is:

Here we've created a class which stores the state of the double pendulum (encoded in the angle of each arm plus the angular velocity of each arm) and also provides some functions for computing the dynamics. The animation functions are the same as above, but we just have a bit more complicated update function: it not only changes the position of the points, but also changes the text to keep track of time and energy (energy should be constant if our math is correct: it's comforting that it is). The video below lasts only ten seconds, but by running the script you can watch the pendulum chaotically oscillate until your laptop runs out of power:

Another animation I created is the elastic collisions of a group of particles in a box under the force of gravity. The collisions are elastic: they conserve energy and 2D momentum, and the particles bounce realistically off the walls of the box and fall under the influence of a constant gravitational force:

How To Create Animated 3d Plots In Python

The math should be familiar to anyone with a physics background, and the result is pretty mesmerizing. I coded this up during a flight, and ended up just sitting and watching it for about ten minutes.

This is just the beginning: it might be an interesting exercise to add other elements, like computation of the temperature and pressure to demonstrate the ideal gas law, or real-time plotting of the velocity distribution to watch it approach the expected Maxwellian distribution. It opens up many possibilities for virtual physics demos...

The matplotlib animation module is an excellent addition to what was already an excellent package. I think I've just scratched the surface of what's possible with these tools... what cool animation ideas can you come up with?

Animations

Matplotlib Animations The Easy Way

Edit: in a followup post, I show how these tools can be used to generate an animation of a simple Quantum Mechanical system.In a previous post, I discussed chaos, fractals, and strange attractors. I also showed how to visualize them with static 3-D plots. Here, I’ll demonstrate how to create these animated visualizations using Python and matplotlib. All of my source code is available in this GitHub repo. By the end, we’ll produce animated data visualizations like this, in pure Python:

In my previous discussion on differentiating chaos from randomness, I presented the following two data visualizations. Each depicts one-dimensional chaotic and random time series embedded into two- and three-dimensional state space (on the left and right, respectively):

I noted that if you were to look straight down at the x-y plane of the 3-D plot on the right, you’d see an image in perspective identical to the 2-D plot on the left. This can be kind of hard to picture in your mind without a visual demonstration, so let’s animate that 3-D plot to pan and rotate and reveal its structure.

Animating Data In Python

Our basic workflow for creating animated data visualizations in Python starts with creating two data sets. Then we’ll plot them in 3-D using x, y, and z-axes. Next we’ll pivot our viewpoint around this plot several times, saving a snapshot of each perspective. Finally we’ll compile all of these static images into an animated GIF.

We’re importing pandas and numpy to work with our data, and random to create the random time series. Next we import pyplot and cm from matplotlib to create our plots and produce sets of colors. Axes3D will be used to render our 3-D plots. IPython.display will display our animated GIFs inline in the IPython notebook. The last three libraries – glob, PIL, and images2gif – are used to grab files in a directory, handle images, and compile a set of images into an animated GIF.

Python

Now, we’ll create two time series, one chaotic and one random. The chaotic data set is produced using the logistic map for 1, 000 generations with a growth rate of 3.99, as I describe in detail here. Then I merge the two series together into a single pandas DataFrame called

Introduction To Plotting With Matplotlib In Python

Next we supply a filename for our animated GIF. This will also serve as the name of a working directory in which we’ll save each snapshot of our plot. Then we call the function to create a 3-D phase diagram (or

Data set, the colors red and blue (to differentiate the chaotic data set from the random data set), axis labels (but only for the x- and y-axes for now), and details for placing the plot’s legend.

Next we’ll define the initial viewpoint perspective for our 3-D plot. In matplotlib, every viewpoint is defined by three attributes: elevation, azimuth, and distance. Elevation is the height above the bottom plane, azimuth is the 360-degree rotation around the plot, and distance is how far away the viewpoint is from the center. These three combine to define a point in 3-D space from which our “camera” will be trained at the center of the plot:

How To Save Matplotlib Animation?

As discussed earlier, we want to start our animation by looking straight down at the x-y plane, so we set the elevation to 90 (high above the plot) and the azimuth to 270 (in line with the z-axis). I offset each of these by 0.1 units because matplotlib axes get a little funky when viewing them

How

There are our x- and y-axes (Population t and Population t+1, respectively), and you can just barely see the z-axis extruding up toward us. The chaotic time series is depicted by red points and the random series by blue points. If you scroll back up to the original 2-D plot, you’ll see that it looks just like this one, other than some slightly different axis scaling.

But we don’t want to stop here. We want to reproduce this snapshot from a range of different perspectives that pan and rotate around the plot to reveal the attractor’s structure. To do this, we’ll create 100 frames (or snapshots of our plot) to combine into an animated GIF. Every good movie needs a good script that defines its action. Here’s ours:

Python Libraries For Creating Interactive Plots

Loop, with one loop per frame of animation – i.e., 100 in total. Let’s unpack it. From n=0 to n=19, we do nothing. This will display the first frame statically for a couple of seconds to give the viewer a chance to soak it in. From n=20 to n=22, we start panning down slowly by reducing the elevation by 0.5 in each time step. Notice that we also removed the axis labels. We’ll keep them turned off until we’re done moving the viewpoint around because they look a bit odd while things are in motion.

From n=23 to n=36, we pan down faster by reducing the elevation by 1.0 in each time step. Then, from n=37 to n=60, we pan down faster still and start to rotate the perspective by increasing the azimuth by 1.1 in each time step. From n=61 to n=64, we pan down slowly while maintaining the same rate of rotation. From n=74 to n=76, we slow down the panning and rotating further to apply the brakes as we reach the final resting position. You could also use an easing function to smooth the animation’s acceleration/deceleration.

When n=77, we add labels for all three axes. The perspective doesn’t change for the final 23 time steps, much like in the beginning, to give the viewer a chance to soak it in. Lastly, in each time step, we title the figure and save a snapshot of the plot to the working directory.

-

Animated 3 D Plots In Python

The animation begins by looking straight down at the x-y plane. Then it starts rotating and panning, revealing the full 3-D structure of this state space. Notice that when we saved the

0 Comments

Posting Komentar