xotix
xotix

Reputation: 530

Savefig closes session

using LsqFit using Plots

function run()
    # Allocate data
    x_data = [ 15.2, 19.9, 2.2, 11.8, 12.1, 18.1, 11.8, 13.4, 11.5, 0.5, 18.0, 10.2,
              10.6, 13.8, 4.6, 3.8, 15.1, 15.1, 11.7, 4.2 ]
    y_data = [ 0.73, 0.19, 1.54, 2.08, 0.84, 0.42, 1.77, 0.86, 1.95, 0.27, 0.39,
              1.39, 1.25, 0.76, 1.99, 1.53, 0.86, 0.52, 1.54, 1.05 ]
    
    t = LinRange(0, 20, 100)
    
    # Plot data
    p = plot(x_data, y_data, seriestype = :scatter)
    
    # Set up model to fit data
    @.model(x, p) = p[1] * ( x/p[2] ) * exp( -( x/p[2] )^p[3] )
    
    # Initial guess
    p0 = [1.5, 1.5, 1.5]
    
    # Fit curve
    fit = curve_fit(model, x_data, y_data, p0)
    
    # Get fitting parameter
    beta = coef(fit)
    
    # Define fitted function
    f(x) = beta[1] * ( x/beta[2] ) * exp( -( x/beta[2] )^beta[3] )
    
    # Plot fitted function
    k = plot!(p, t, f.(t))
    
    # Display plot
    display(p)
    
    # Safe plot
    savefig("plot.png")
end

if I open a REPL session and use Revise to includet the above and call run(), I see the plot window open and close instantly. If I uncomment savefig() it stays open. I'm a bit confused about this behaviour.

Upvotes: 2

Views: 138

Answers (1)

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42244

If you want to both save the plot and display it using the GR backend simply reverse the order of functions so it should be:

    # Safe plot
    savefig("plot.png")

   # Display plot
   display(p) 

It seems that saving the figure requires rendering it, and after saving the user interface gets closed. With this reversed order everything will work as expected.

Upvotes: 2

Related Questions