Plotting distributions with StatsPlots in a for loop

Hey guys! I need to understand why this does not plot inside a for loop but does plot ok outside:

using Distributions, StatsPlots


dists = Iterators.product(0:1:2, 0:0.2:1) |> collect

for i in dists
    plot!(Normal(i[1], i[2])) # also tried with plot() and also tried instantiating a plot() before the loop
end

One way is to add a plot!() at the end:

julia> x = rand(10);

julia> plot()

julia> for i in 1:3
         plot!(x)
       end

julia> plot!()

Maybe this is more elegant and useful in some situations:

julia> p = plot();

julia> for i in 1:3
         plot!(p,rand(10))
       end

julia> plot!(p)



Try inserting the plot! command inside a display() command.

1 Like

Yes, it works :slight_smile:

julia> plot()

julia> for i in 1:3
          display(plot!(rand(10)))
       end


1 Like

thank you all!

I think the “official” way of doing this is current()

1 Like

Testing current() it seems to display only the final result after the loop, but not the intermediate plot updates, which can be of interest to visualize animations with some delay between plots:

plot()
for i in 1:5
    sleep(0.5)
    display(plot!(rand(10)))
end
1 Like

Yes sorry I read this as the classic “I’m plotting in a loop and can’t see the output” issue, for intermediate plots indeed display is the way to go

1 Like