plot – Elektromagnetisme http://elektromagnetisme.no The home of FYS1120 Mon, 20 Oct 2014 11:23:54 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.3 28429679 Animating plots and waves in Python using matplotlib http://elektromagnetisme.no/2011/04/03/animating-plots-and-waves-in-python-using-matplotlib/ http://elektromagnetisme.no/2011/04/03/animating-plots-and-waves-in-python-using-matplotlib/#comments Sun, 03 Apr 2011 16:34:14 +0000 http://mindseye.no/?p=393 Continue reading ]]> matplotlib is an amazing framework to do visual plots in Python. It compares well with GnuPlot and beats Matlab’s plotting abilities by having more features. Although it does lack some 3D support, you may simply choose a different framework for 3D plots thanks to Python’s flexibility . In which case I would recommend Mayavi as a superb 3D plotting engine which I have written about before.

But now, let’s have a look at matplotlib’s animation capabilities. The script below shows a very easy approach to animation in matplotlib. This results in an animation of the standing wave shown here:

The script is as follows:

from matplotlib.pylab import *  # pylab is the easiest approach to any plotting
import time                     # we'll do this rendering i real time

ion()                           # interaction mode needs to be turned off

x = arange(0,2*pi,0.01)         # we'll create an x-axis from 0 to 2 pi
line, = plot(x,x)               # this is our initial plot, and does nothing
line.axes.set_ylim(-3,3)        # set the range for our plot

starttime = time.time()         # this is our start time
t = 0                           # this is our relative start time

while(t < 5.0):                 # we'll limit ourselves to 5 seconds.
                                # set this to while(True) if you want to loop forever
    t = time.time() - starttime # find out how long the script has been running
    y = -2*sin(x)*sin(t)        # just a function for a standing wave
                                # replace this with any function you want to animate
                                # for instance, y = sin(x-t)

    line.set_ydata(y)           # update the plot data
    draw()                      # redraw the canvas

I’ve commented each line, since the script is fairly small, but let’s outline a few important things.

First of all, you need to disable interactive mode with

ion()

This makes it possible to animate, but disables all the button controls in matplotlib’s figure window.

Furthermore, we need to assign our plot to a variable (or pointer if you like), named line. This is done by plotting some dummy data:

line, = plot(x,x)

Note the comma after “line”. This is placed here because plot returns a list of lines that are drawn. Since we draw only one line we unpack only this by placing a comma and nothing else after “line”. If you plot multiple lines at once you may unpack them together by issuing a command like this:

line_a,line_b,line_c = plot(...

This plotting makes our axes aligned to the dummy data (in this case y = x). To make sure we have enough room, we manually set the limits of our y axis:

line.axes.set_ylim(-3,3)

Finally, we do our calculations and eventually change the y-data for each time step. After this, we draw everything back onto the canvas. This is done through the following two lines:

    line.set_ydata(y)           # update the plot data
    draw()                      # redraw the canvas

That’s it. Your animation should now look like the one above.

Saving the animation to a  file

Saving everything to file is fairly simple with the savefig command. You can save all the frames as images and then convert them to video using your favorite video editor. I recommend using ffmpeg from command line or Blender (which also does 3D). There are surely easier tools out there, but I find the work flow using ffmpeg and Blender quite quick, and they are also useful tools for many other tasks.

I’ve made the script animation ready below, and there’s really just one important thing to note: Earlier we showed the animation in real time. Saving all the images in real time lags badly and many frames are dropped. Because of this, we now set a delta time between each frame and iterates over each and every frame to make sure we have enough data for a smooth video.

Feel free to use the script below as it suits you:

from matplotlib.pylab import *  # pylab is the easiest approach to any plotting

ion()                           # interaction mode needs to be turned off

fig = figure(figsize=(16,9),dpi=80)     # create a figure in 1280 x 720 pixels
                                # this is not as simple as it could be, but
                                # it is like this because matplotlib is focused
                                # on print, not screen

x = arange(0,2*pi,0.01)         # we'll create an x-axis from 0 to 2 pi
line, = plot(x,x)               # this is our initial plot, and does nothing
line.axes.set_ylim(-3,3)        # set the range for our plot

t = 0                           # this is our relative start time
dt = 0.04
i = 0
while(t < 5.0):                 # we'll limit ourselves to 5 seconds.
                                # set this to while(True) if you want to loop forever
    y = -2*sin(x)*sin(t)        # just a function for a standing wave
                                # replace this with any function you want to animate
                                # for instance, y = sin(x-t)

    line.set_ydata(y)           # update the plot data
    draw()                      # redraw the canvas

    t = t + dt                  # increase the time
    i = i + 1                   # increase our counter

    # save the figure with a 4-digit number
    savefig("outdata/blah" + '%04d' % i + ".png")
]]>
http://elektromagnetisme.no/2011/04/03/animating-plots-and-waves-in-python-using-matplotlib/feed/ 6 393
The beauty of Mayavi http://elektromagnetisme.no/2010/10/07/the-beauty-of-mayavi/ http://elektromagnetisme.no/2010/10/07/the-beauty-of-mayavi/#comments Thu, 07 Oct 2010 07:07:53 +0000 http://mindseye.no/?p=214 Continue reading ]]>

Four charges with different magnitude plotted in 3D using Mayavi

In one of my earlier posts about Mayavi, I wrote about how you could visualize 2D field line plots using the flow function. At the end of that post I added that Mayavi is actually best at 3D plotting, and to follow up on that I’ll show you some of these plots with a few example Python scripts you might try out on your own.

First of all, you might want to know how to install Mayavi. For those lucky ones of you who have freed yourself and jumped on the Linux bandwagon, installing Mayavi should be quite easy. If you are using Ubuntu in particular, you may just install the package mayavi2 using either Synaptic or apt-get. If you are on Windows or Mac, you may either install Enthought’s own Python distribution (EPD) or give a shot at compiling on your own. Just note that EPD is quite expensive, even though all its components are open source, but if you are a student or academic user you could go ahead and download the academic version for free. It is basically the same as the commercial one, but with an academic license. (Kudos to Enthought for both making Mayavi open source, building an business model around it and still providing a great solution for students!)

Now, Enter 3D!

The way you do your plots in Mayavi depends on what you want to express. Most likely, you would prefer to show some simple plots giving just the necessary amount of information to tell you how the electric field behaves around your charges. A simple example of this is shown below:

Four charges in a Mayavi plot

The simple plots often give you a great perspective about what happens in the electric field

On the other hand, you might want to give a strong visualization to show off the density and beauty of an electric field. In such a case, increasing the resolution of the flow/streamline seeds gives you a greater amount of field lines, which could result in plots like this:

An highger seed resolution gives a more dense plot.

Note that the plot shows the same four charges as above, but from a different angle and, of course, with more field lines.

The greatest part of using Mayavi to visualize these plots, however, comes from the fact that you may rotate the plot in real time in the Mayavi scene view. This gives you great control and insight of what you are plotting as you may rotate it as if it was a physical object in front of you. To show how interesting this may be, I’ve created a short video rotating around the same plot as above, recorded using Mayavi’s animation features:

You may even animate the charges individually, showing you what happens when a charge moves through space.

Note that the video below shows some artifacts around the charges. I believe I could have tweaked the settings a bit more to avoid these, but I decided it was good enough for the purpose of showing Mayavi’s capabilities.

If you would like to test out these plots on your own, you can download the source code here:

And if you couldn’t get enough of those field line plots, here are all the above and a some more, stacked in one set:

Four charges in a Mayavi plot High resolution plot of four charges in a square Low resultion plot of four charges perfectly aligned in a square Using planes and spheres together as seeds yields more interesting results. A medium resolution dipole plot with spheres as seeds. Using a plane as a flow/streamline seed between the two charges in a dipole ]]>
http://elektromagnetisme.no/2010/10/07/the-beauty-of-mayavi/feed/ 7 214