Plots do not display, unless I call gui(), when using custom sysimage

I have created a custom sysimage that contains Plots, as explained here

https://julialang.github.io/PackageCompiler.jl/dev/examples/plots.html

(see [1] below for complete details).

If I start Julia from the REPL using that sysimage and I try to plot

using Plots
plot(rand(1))

I get

Plot{Plots.GRBackend() n=1}

Same thing happens (i.e., no plot is displayed) even if I do

p1 = plot(rand(3))
display(p1)

I need to do gui() (or gui(plot(rand(1))) or plot(rand(1), show = true)) for the plot to be displayed.

If I start Julia without the sysimage, or with other sysimages I’ve created that do not contain Plots, everything works as expected (plot displays the plot in a window without needing to use gui). And I’d be willing to bet this did not happen to me before (e.g., with Julia 1.8.2).

I think I have broken something, but I just reinstalled Julia from scratch and removed the ~/.julia directory before installing packages again, so I can’t understand what is happening.

(Note: a somewhat similar thing has been asked about Makie: Makie doesn't display plot when using a custom Julia sysimage, but my question is about Plots —I do not have Makie installed).

Julia> versioninfo()
Julia Version 1.8.4
Commit 00177ebc4fc (2022-12-23 21:32 UTC)
Platform Info:
  OS: Linux (x86_64-linux-gnu)
  CPU: 8 × Intel(R) Xeon(R) CPU E3-1505M v5 @ 2.80GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-13.0.1 (ORCJIT, skylake)
  Threads: 1 on 8 virtual cores


(@v1.8) pkg> st --manifest Plots
Status `~/.julia/environments/v1.8/Manifest.toml`
  [91a5bcdd] Plots v1.38.0

@v1.8) pkg> st --manifest PackageCompiler
Status `~/.julia/environments/v1.8/Manifest.toml`
  [9b87118b] PackageCompiler v2.1.2

[1] Custom image creation and use:

  1. Create file precompile_plots.jl that contains
using Plots
p = plot(rand(2,2))
display(p)
  1. Start Julia and type
using PackageCompiler
create_sysimage(["Plots"], sysimage_path="sys_plots.so", precompile_execution_file="precompile_plots.jl")
  1. Finally, start Julia as

julia --sysimage sys_plots.so

and, in the REPL type

using Plots
plot(rand(1))

Answering my own question, an analogous to what has to be done with Makie (Makie doesn't display plot when using a custom Julia sysimage), one can solve this by running Plots.__init__() after loading Plots.

(In addition it seems also that if the sysimage contains IJulia, the above will not work, nor will gui nor plot(p, show = true); I think this makes sense, but I had a couple of sysimages that, accidentally, included IJulia).

I’ve made a pull request suggesting the use of Plots.__init__() in the example in Creating a sysimage for fast plotting with Plots.jl · PackageCompiler.