juliaijulia-notebookjulia-plots

How do I add plots to separate figures using for loops in Julia


I am trying to create two separate figures for which I'd like to add plots to each using a for loop.

using Plots
gr()
Plots.theme(:juno, fmt = :png)

x = [1,2,3,4]
y = [8,7,6,4]

pt1 = plot()
pt2 = plot(reuse = false)
for i in 1:5
    pt1 = plot!(x, i*y)
    pt2 = plot!(x, y/i, reuse = false)
end

display(pt1)
display(pt2)

I'd expect to get two figures as if I were doing them separately: Test of pt1 Test of pt2

But instead what I get is two figures with all the plots for pt1 and pt2. Actual results

I tried looking into using push!, but the examples I found were making gifs, which is not what I'm trying to do. This seemed like the most straightforward way that should work, I must just be missing something obvious.


Solution

  • plot! can take plot handle as the first argument so it should be plot!(pt1, x, i*y).

    Here is the full corrected code:

    using Plots
    gr()
    Plots.theme(:juno, fmt = :png)
    
    x = [1,2,3,4]
    y = [8,7,6,4]
    
    pt1 = plot()
    pt2 = plot()
    for i in 1:5
        plot!(pt1, x, i*y)
        plot!(pt2, x, y/i)
    end
    
    display(pt1)
    display(pt2)
    

    And here is the outcome:

    enter image description here

    enter image description here