Search code examples
juliajuno-ide

What is the best way to plot multiple ODE solutions on the same graphic in Julia?


I have an ODE and wanted to solve it and plot the solution for some initial conditions. At the beginning, I decided to make a "for" to increase the value of the initial condition and then plot the solution, one on top of the other.

using DifferentialEquations, Plots

for i = -2.00:0.25:2.00
    f(x,p,t) = x-x^3
    x0 = i
    tspan = (0.00,2.00)
    prob = ODEProblem(f,x0,tspan)
    sol = solve(prob)
    if i==-2.00
        plot(sol,linewidth=4, title="Solution",
             xaxis="t",yaxis="x(t)",legend=false)
    else
        plot!(sol,linewidth=4, title="Solution",
            xaxis="t",yaxis="x(t)",legend=false)
    end
end
savefig("Graphic.png")

Is there a better way to do this?


Solution

  • You can create an empty plot with just the title, axis label, etc and then populate the plot with the solutions:

    # main plot settings
    plot(linewidth=4, title="Solution",
         xaxis="t",yaxis="x(t)",legend=false)
    
    for i = -2.00:0.25:2.00
        f(x,p,t) = x-x^3
        x0 = i
        tspan = (0.00,2.00)
        prob = ODEProblem(f,x0,tspan)
        sol = solve(prob)
    
        # add to existing plot
        plot!(sol)
    end