In [1]:
using Plots

Animations in Julia with Plots

Reference: https://docs.juliaplots.org/latest/animations/

A quick intro to animations using Plots in Julia. It turns out it's super simple.

You can animate any plot by adding the @animate or @gif macros to a loop. Let's do an example without any abstractions like recipes or whatever and get right to it.

@animate gets added to the beginning of a loop, and what it does is it saves the plot output at each iteration into a temporary .png file. Each of these snapshots form an individual frame of your animation.

You can then call the gif function to display the frames of your animation as a repeating gif:

In [2]:
# Simple dataset of 50 random numbers
y = rand(50)

# Use the @animate macro in front of a loop to create each frame of your animation
anim = @animate for i in 1:50
    # At each iteration we will plot a new subset of the data
    # I set the xlimits and ylimits so the x/y axes don't autofit as the data grows
    plot(y[1:i], 
         xlims=(1,50),
         ylims=(0,1))
end

# Save the animation as a gif and display it
gif(anim)
┌ Info: Saved animation to 
│   fn = /Users/nelsontang/repos/julia-animation/tmp.gif
└ @ Plots /Users/nelsontang/.julia/packages/Plots/Xv2qA/src/animation.jl:114
Out[2]:

So we can already see the gif repeating in an infinite loop and it doesn't look very appealing. You can set the fps attribute to set the frames per second a little slower. And by default it saves this as tmp.gif in the local directory, you can change the filename to something else with the second argument:

In [3]:
gif(anim, "new_animation.gif", fps=12)
┌ Info: Saved animation to 
│   fn = /Users/nelsontang/repos/julia-animation/new_animation.gif
└ @ Plots /Users/nelsontang/.julia/packages/Plots/Xv2qA/src/animation.jl:114
Out[3]:

That's it! To animate something in base plots you simply call the @animate macro in front of a loop, and within each loop you create each frame of the animation.

And for convenience you can combine the @animation for...end |> gif call into a @gif call:

In [4]:
@gif for i in 1:50
    plot(y[1:i], xlims=(1,50), ylims=(0,1))
end
┌ Info: Saved animation to 
│   fn = /Users/nelsontang/repos/julia-animation/tmp.gif
└ @ Plots /Users/nelsontang/.julia/packages/Plots/Xv2qA/src/animation.jl:114
Out[4]:
In [ ]: