Animation in Julia.
Animated plots in Julia can be created using the matplotlib tools that we know from Python.
The idea is the same. There are three steps to creating an object that will contain the animation:
- draw the empty figure
- define an init function, and an animate function, that will draw the successive frames
- create the animation using the FuncAnimation fucntion (which calls init and animate)
This object is then saved as an MP4 file, which can then be played in the notebook using an html command.
For more ideas on animation, take a look here: http://nbviewer.jupyter.org/github/tom26/JuliaFun/blob/master/2D%203-Body%20Problem.ipynb
Let's do a simple animation, drawing 3 lines across a plot.
First, tell Julia the tools we need to load in:
using PyPlot
using PyCall
@pyimport matplotlib.animation as anim
We first construct the empty figure. For convenience, we define 3 global data structures called lines.
#Construct Figure and Plot Data
fig = figure("MyFigure",figsize=(10,10))
ax = axes(xlim = (0,10),ylim=(0,10))
global line1 = ax[:plot]([],[],"r-")[1]
global line2 = ax[:plot]([],[],"g-")[1]
global line3 = ax[:plot]([],[],"b-")[1]
PyObject <matplotlib.lines.Line2D object at 0x7f3be6f4d2e8>
We now define the init function, which sets the data for the first frame
# Define the init function, which draws the first frame (empty, in this case)
function init()
global line1
global line2
global line3
line1[:set_data]([],[])
line2[:set_data]([],[])
line3[:set_data]([],[])
return (line1,line2,line3,Union{}) # Union{} is the new word for None
end
init (generic function with 1 method)
Next is the animation function, which will draw each frame of the animation using index i.
In this case, we just draw three lines. The first is along the line x=y, going from point (0,0) to (i/10,i/10).
# animate draws the i-th frame, where i starts at i=0 as in Python
function animate(i)
global line1
global line2
global line3
x = (0:i)/10.0
line1[:set_data](x,x)
line2[:set_data](1+x,x)
line3[:set_data](2+x,x)
return (line1,line2,line3,Union{})
end
animate (generic function with 1 method)
Now we create the animation object by calling the Python function FuncAnimaton.
myanim = anim.FuncAnimation(fig, animate, init_func=init, frames=100, interval=20)
PyObject <matplotlib.animation.FuncAnimation object at 0x7f3be65cc5c0>
This is converted to an MP4 movie file and saved on disk in this format.
myanim[:save]("3Lines.mp4", bitrate=-1, extra_args=["-vcodec", "libx264", "-pix_fmt", "yuv420p"])
Finally, we display the movie in a Julia cell as follows. Note it has animation controls for the user.
# Function for creating an embedded video given a filename
function html_video(filename)
base64_video = base64encode(open(readbytes, filename))
"""<video controls src="data:video/x-m4v;base64,$base64_video">"""
end
display("text/html", html_video("3Lines.mp4"))