The plot (with Plots pkg) not displayed, if plot(...) is not the last operator

This works as expected:

using Plots
x = 0:0.1:1
y = sin.(2π*x)
@show plot(x, y, lw=3)

and this does not display anything, no produce any error messages:

@show plot(x, y, lw=3)
and this works again (workaroung just found)
@show plot(x, y, lw=3)

a=1 is just an example: it is the same with any operator(s).
@show plot added just to be sure the line was executed, and it returns in both cases:
julia> plot(x, y, lw=3) = Plot{Plots.GRBackend() n=1}

Julia 1.3, Atom, Win10
Julia 1.3.1, Atom, MacOS
For the backend, I have tested with GR, PyPlot, PlotlyJS on Mac and GR on Win

Is that expected behavior? If yes, why?

Yes it is - this is not unique to plots, if you execute a block of code what’s shown is the value of the statement executed last (e.g. if you added 1+1 somewhere in your code block you’d never see the 2, while if you add 1+1 as your last line the result gets printed).

If you want to show a plot within a line of code that you’re executing, you should call display() on it. Alternatively, you can assign your plot to a variable like p = plot(rand(100)), and then just add p as your last line instead of the plot!() call you currently have.


@nilshg thank you for the explanation and for the suggestions.

Actualy my problem arose as I wanted for plot from a loop (in a function), and now I have found two more discussions on exactly that problem How to plot in for loop (or map) and Plotting from within a loop using GR? .

My prefered solution is to call current() or plot!() as the last code line.

You can call display on your plot object to have it display to a screen.

1 Like

display doesn’t work for me in Juno, maybe because I’m using return somewhere in the function, or because I have the plot pane disabled.