How do I make an "animated" updating plot using Plots.jl in JuPyTeR?

1.4k views Asked by At

I would like to show a plot that is updating every iteration of the loop.

For example say I want to show a random walk.

using Plots
using IJulia

walk = [0.0]
for ii in 1:100
    step = 2rand() - 1.0
    push!(walk, walk[end]+step)
    plot(1:length(walk), walk) |> IJulia.display
    sleep(0.2) #For demo purposes
end

Final output: random walk plot

I know IJulia.display is the function to force a plot to be displayed now, (rather than it being diplayed automatically if it is the final expression).

But this just gives me 100 plots. They are not updating.

I don't want a true animation, just an updating plot. So I don't think the Plots animate! stuff is relevant The random walk is just an example, what I really want to do is monitor the status of a long running process.

1

There are 1 answers

0
Frames Catherine White On

What you are missing is the function to clear the output before you should your next plot.

This is IJulia.clear_output(). And the really trick is that it takes an bool arguemnt that defaults to false, but if you set it true will cause the clearing to be delayed until the next output is produced. This will stop fliggering.

So with that your code becomes:

walk = [0.0]
for ii in 1:100
    step = 2rand()-1.0
    push!(walk, walk[end]+step)
    IJulia.clear_output(true) #Passing true says to wait until new ouput before clearing, this prevents flickering
    plot(1:length(walk), walk) |> IJulia.display
    sleep(0.2)

end

This isn't 100% ideal, since clearing the output before you redraw will clear everything else you displayed prior. But it is often convenient enough.