Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using plot within a script in julia

Tags:

julia

plots.jl

I've been prototyping some julia code in a Jupyter notebook, but it's outgrown the notebook format and I want to put it in a script in order to organise it properly. However, I can't work out how to get Plots to work in a script, and can't find any documentation about it.

Here's a minimal not-working example:

using Plots
gr()
display(plot([1,3,2]))
println("here")

This code takes 20-30 seconds to import Plots, then opens a window but immediately closes it again, prints "here", and exits. I can't use ctrl-C while the import process is happening.

So, I have three questions:

  • How do I prevent the plot window from closing as soon as it opens? What I want is for the script to block or (ideally) enter an event loop until the window is closed, and terminate after that.

  • Can the extremely long import time be reduced somehow?

  • Does any documentation exist for using Plots outside of a Jupyter environment?

If it makes a difference, I'm using julia 1.1.1 on a Mac.

like image 546
N. Virgo Avatar asked Oct 15 '22 14:10

N. Virgo


1 Answers

The most natural way to achieve the workflow you're looking for in the first bullet is to use Juno or VS Code. Suppose in your working directory you have the following code in a file script.jl:

using Plots
gr()
display(plot([1,3,2]))

hello = "world"

println("here")

Now fire up Juno or VS Code and launch the integrated Julia REPL. From the Julia REPL, you can use include to source your script:

julia> include("script.jl")
Plot{Plots.GRBackend() n=1}
here

Now your script has been completely run and the plot is available for viewing in the plot pane (this is true for both Juno and VS Code). Now you can continue to include other files in the REPL or run other code interactively. Note that variables defined in script.jl are available for use:

julia> hello
"world"

EDIT:

If you run a script using the -i option (for interactive), the plot GUI will stay open and a REPL will launch after the script is done running:

$ julia -i script.jl

The various options to the Julia executable can be found here, or can be found by typing $ julia --help in a terminal.

like image 58
Cameron Bieganek Avatar answered Oct 21 '22 03:10

Cameron Bieganek