Plotting in a loop

I have some data that are updated in a for-loop. I need to plot them for each iteration of the cycle, in the same graph (that is, clear the old data and plot the new).
For sure this problem is very common and easy to solve, however I can’t find any straightforward example online.
I’m using Jupyter as environment and PyPlot for “static” graphs (I mean, diagrams that don’t change over time).

Here’s a pseudo-code to understand what I need:

for i in 1:100
  clear_plot()
  plot(sin(i*x))
  sleep(1)
end

The above code should plot a sine wave, wait 1 second, replace it with a different one, wait another second, and so on.
Can you help me? Thanks!

2 Likes

You want IJulia.clear_output(true)

See here for a fairly extensive discussion of your question.

2 Likes

Aren’t you refering to Plots.display(plot(sin(i*x))) to update the plot within the loop?

1 Like

In my notebook it doesn’t update the plot, instead it creates a new plot under the previous one.
A working solution, as pointed out by @cortner, is IJulia.clear_output(true)

Here’s a complete code that works perfectly in Jupyter, I hope it helps other newbies like me:

using Plots
for i in 1:20
    IJulia.clear_output(true)
    x = linspace(0,2*pi,1000); y = sin.(i*x)
    Plots.display(plot(x,y, color="red"))
    sleep(0.1)
end
println("Done!")
8 Likes