# Plotting multiple traces on a single plot in IJulia/Jupyter using a loop

Does any know how to add multiple traces to a plot in Jupyter?

The following code works fine in Juno. It generates a series of offset sine waves in the same plot.

``````using GR

x=collect(0:0.1:2pi)
y=sin.(x)

plot(x,y)

for i=1:10
oplot(x,y.+i/10)
end
``````

However, in Jupyter, no plot is produced. It seems anytime a cell ends in something other than the direct call for a plot, the plot does not show up when the cell is run.

Running Julia 1.0.3

Found a solution using a function. Not sure why the original does not work (maybe a scope related issue?).

Correction: the code below only worked once by accident, not sure what I did. For the correct implementation see Simon_Bolland’s response below

``````using GR

x=collect(0:0.1:2pi)
y=sin.(x)

function tryplot()
plot(x,y)
for i=1:10
z=oplot(x,y.+i/10)
end
return z
end

tryplot()
``````

Still, if I try this code in Jupyter:

``````using GR

x=collect(0:0.1:2pi)
y=sin.(x)

plot(x,y)
println("Hello")
``````

The only output from running the cell is “Hello”. If anyone has any insight on why no plot shows up in the latter case it would be appreciated.

Jupyter defaults to only showing the last value in a cell

Try

``````using GR

x=collect(0:0.1:2pi)
y=sin.(x)

display(plot(x,y))
println("Hello")
``````

to force the plot to be shown

1 Like

Awesome. Thanks!. Now, any idea how to make that work in a loop so that all traces are plotting in the same plot?

``````using GR

x=collect(0:0.1:2pi)
y=sin.(x)

display(plot(x,y))
for i=1:10
display(oplot(x,y.+i/10))
end
println("Hello")
``````

The above generates 10 plots. All I need is the last one.

``````using GR

x=collect(0:0.1:2pi)
y=sin.(x)
p=nothing
for i=1:10
p=oplot(x,y.+i/10)
end
display(p)
println("Hello")
``````
1 Like

Excellent! Is the line below storing an array of svg images in p? If not, is there a way to do that so that the array elements (svg images) can be referenced/used elsewhere?

``````p=oplot(x,y.+i/10)
``````

This overwrites p with the plot so far on each loop. If you want all the intermediate plots you could set up an array and do p[i]=oplot(x,y.+i/10) but I’ve shut pc down for the night so can’t look for correct element type - let me know if you need this and I’ll look tomorrow

I’m not finding the element type so any input you can provide tomorrow would be appreciated. Thanks!

Try this:

``````using GR

x=collect(0:0.1:2pi)
y=sin.(x)

p=Array{GR.SVG}(undef,1,11)
p=plot(x,y)

for i=1:10
p[i+1]=oplot(x,y.+i/10)
end
display(p)
display(p)
display(p)
println("Hello")
``````
1 Like

Works great. Many thanks!

A quick addition for the benefit of anyone reading this later. A plot statement seems to be needed before the loop so the oplot function has an image to write over.

``````using GR

x=collect(0:0.1:2pi)
y=sin.(x)
p=nothing
plot(x,y)    #<===============
for i=1:10
p=oplot(x,y.+i/10)
end
display(p)
println("Hello")
``````