Jupyter, plot, and last value?

It seems to me that to get a plot in a Jupyter notebook (or JupyterLab), a plot function call has to be the last value. Is that so?

using Plots
const xs = [-pi + i*(pi/10) for i in 0:20]
for j = 1:3
  ys = sin.(j*xs)
  plot!(xs,ys)
end
ys = cos.(xs)
#plot!(xs,ys) # <-- I need this to get a plot

I wonder what the standard solution is.

I’m just new to Jupyter and I’m using CoCalc, which says it uses Julia 1.6 .

Hey there and cool you are using Jupyter!
In my experience, Julia cells executed in Jupyter is that there is an implicit return from the last executed function in the cell.
If you want the plot displayed, I might suggest rather doing something like this:

using Plots
const xs = [-pi + i*(pi/10) for i in 0:20]
p = plot()
for j = 1:3
  ys = sin.(j*xs)
  plot!(xs,ys)
end
ys = cos.(xs)
display(p)

That should display the plot.
I don’t have a notebook open right now so if it fails, I apologize!
Let me know if this helps.

~ tcp :deciduous_tree:

2 Likes

display will do the trick, but needs an explicit plot object (which I think is good to have anyway to reduce confusion). A more direct alternative is to call current()

1 Like

What @TheCedarPrince is correct. Conceptually, a plot (or plot!) call just creates a Plot, just like x = 5 creates an Int. When x = 5 is at the end of a cell, the value 5 gets automatically displayed by Jupyter, and the same for a plot call - the returned Plot object gets displayed, which happens to be the image of the plot. If the x = 5 assignment happened earlier in the cell, but we wanted the value of x to be shown when we run the cell, we could place an extra line at the end of the cell that just said x - and the same applies for the plot object p. (The explicit call to display in the TheCedarPrince’s code is not necessary - just having p as the last value of the cell will automatically have it be displayed - but doesn’t hurt either.)

1 Like

I do it like this

plot()
for i=1:3
   plot!(<stuff>)
end
plot!()
2 Likes

@TheCedarPrince
That’s exactly what I was looking for! Thanks. I suppose

   plot!(p, xs, ys) # <-- explicitly use "p"

is what you meant, right?

Thank you all for your input!

I wonder which document I should look at? All tutorials I’ve found on the Net show code like mine (without an explicit plot object).

I’m still new to Julia and indeed when I first saw the plot function, I was delighted that it’s so simple and yet versatile. At the same time, I was a bit surprised that it didn’t involve a plot object. (What if I wanted two separate plots?)

Julia’s online documentation is superb, IMHO. Both the core language and major packages. Check out Combining Multiple Plots as Subplots from the Julia Plots Tutorial.

1 Like

If this is the last line of the cell, you can just put

p

since the last-executed expression is automatically displayed as the cell output. That’s also why putting current() (with no display) works.

1 Like