# Plotting figures and updating in loop

Hi, I want to create plots of a function in a for loop, in separate windows (p1, p2), but it is displayed in a single window.

I used MATLAB and there I used figure (), to create empty figures. in this case I have used plot (), but it does not solve the problem.

this is the code

``````using Plots

function sx(E)
a(x) = x^2 + E
b(x) = x + E
p1   = plot!(a)
p2   = plot!(b)
end

E = [12
24]

p1 = plot()
p2 = plot()

for i = 1:2
sx(E[i])
end

display(p1)
display(p2)
`````` First, the way to update plots is to use `plot!` with the main plot passed in as its first argument so rewriting your code would look like this:

``````p1 = plot(title = "Plot 1")
p2 = plot(title = "Plot 2")

function sx(E)
a(x) = x^2 + E
b(x) = x + E
plot!(p1, a)
plot!(p2, b)
end
``````

The default `gr()` backend doesn’t support multiple windows that I know of but the `pyplot` backend does by setting `reuse=false` in `p1` and `p2` so the full code would look like this:

``````using Plots
pyplot() # Switch to the pyplot backend. Needs to be installed first.

p1 = plot(title = "Plot 1", reuse = false)
p2 = plot(title = "Plot 2", reuse = false)

function sx(E)
a(x) = x^2 + E
b(x) = x + E
plot!(p1, a)
plot!(p2, b)

end

E = [12
24]

sx.(E) # More Julia way of doing your for loop

p1
p2
``````
2 Likes

thanks, but only plot 2 is displayed, plot 1 is not visible

You need to either evaluate the lines

``````p1
p2
``````

sequentially or do

``````display(p1)
p2
``````

if you want two plots in the plot pane. This is because running a code snippet will return whatever the return value of the last line is, and nothing before that.

If you want both plots on one figure you need to do `plot(p1, p2)`.

2 Likes

The Julia VSCode extension overrides how plots are displayed. Turning off the VS Code setting `julia.usePlotPane` will make the plots open in their own window instead of the VS Code plot pane.

Personally, I think you should just plot both in the same window since what your trying to do isn’t really supported by ` Plots`. I wouldn’t expect Julia and Matlab to have the same features or best practices.

`plot(p1, p2)`

`plot(p1, p2, layout=(2,1))`

1 Like

``````using PyPlot