newtothis
newtothis

Reputation: 525

Multiple plots on the same figure julia

I am writing a Julia program which iteratively runs another function, and will give me two sets of results. I want to plot these results and right now what I am doing is to plot the results of each for loop separately which gives me about 20 plots for the example below: Say something like this:

for i in 1:10
    x1,y1 = first_function(a,b,c)
    plot(x1,y1)
end
for j in 1:10
    x2,y2 = second_function(a,b,c)
    plot(x2,y2)
end

I have tried to use the plot!() command instead but this gives me all 20 plots on the same plot, which I don't want. What I would like to do is to plot the results of both functions on the same plot, for each iteration. For instance I want 10 plots, one for each iteration where each plot has results of both first_function() as well as second_function. I have tried the following instead:

for j in 1:10
    x1,y1 = first_function(a,b,c)
    x2,y2 = second_function(a,b,c)
    plot!(x1,y1)
    plot!(x2,y2)
end

However, this doesn't seem to work either.

EDIT: Based on an answer I received, I was able to figure out that the following does the trick:

for i in 1:10
    x1,y1 = first_function(a,b,c)
    x2,y2 = second_function(a,b,c)
    plot(x1,y1)
    plot!(x2,y2)
end

This generates a new plot at the end of each iteration of the loop, which is what I wanted.

Upvotes: 4

Views: 3994

Answers (1)

Nils Gudat
Nils Gudat

Reputation: 13800

As you have found out, plot() creates a new plot, while plot!() plots onto the currently active plot.

All you need to do is be explicit about when you want to do what, and if you're using plot!() also be explicit about which plot object you want to plot to. So something like:

p1 = plot()
p2 = plot()

for i in 1:10
    plot!(p1, first_function(a, b, c)...)
    plot!(p2, second_function(a, b, c)...)
end

then p1 should have 10 lines showing the result of first_function, and p2 10 lines with results of the second function.

It is not clear to me whether you want both of these plots to appear on the same figure, but if you do then plot(p1, p2) will create a figure with two subplots.

Upvotes: 5

Related Questions