Author

Josh Day

Published

May 7, 2021

Animations with Plots.jl

ENV["GKSwstype"] = "nul"
using Plots, Random

Why Animations are Great

Effective communication represents an undervalued competency in data science. Animations tell a story that static images are unable to tell by adding an extra dimension (often time). Beyond narrative value, animated visualizations demonstrably enhance audience engagement compared to static imagery, making them valuable for presentation purposes.

Animations with Plots.jl

Plots.jl offers unified syntax across multiple plotting backends while providing straightforward utilities for generating animated GIFs. The authors recommend using Pluto notebooks for animation development, as visualizations render directly in the notebook environment.

Method 1: The @gif Macro (Simplest)

@gif for i in 1:50
    plot(sin, 0, i * 2pi / 10)
end
[ Info: Saved animation to /tmp/jl_xYFqBYjYru.gif

Add conditional flags to control frame inclusion:

@gif for i in 1:50
    plot(sin, 0, i * 2pi / 10)
end when i > 30
[ Info: Saved animation to /tmp/jl_j8FWdYTgTE.gif

Method 2: The @animate Macro (FPS Control)

anim = @animate for i in 1:50
    Random.seed!(123)
    scatter(cumsum(randn(i)), ms=i, lab="", alpha = 1 - i/50,
        xlim=(0,50), ylim=(-5, 7))
end

gif(anim, fps=50)
[ Info: Saved animation to /tmp/jl_FgVCxMhQ1g.gif

Method 3: Direct Plots.Animation (Maximum Control)

a = Animation()

for i in 1:10
    plt = bar(1:i, ylim=(0,10), xlim=(0,10), lab="")
    frame(a, plt)
end

gif(a)
[ Info: Saved animation to /tmp/jl_HSBElGxEZe.gif

Additional Resources