Search code examples
plotjuliadifferential-equations

Julia Plots; how can I individually plot coupled equations graphs?


I am learning Julia, specifically how to solve coupled differential equations. I am looking at the document page for differential equations and have taken this code from it:

using DifferentialEquations


function lorenz(du,u,p,t)
    du[1] = 10.0*(u[2]-u[1])
    du[2] = u[1]*(28.0-u[3]) - u[2]
    du[3] = u[1]*u[2] - (8/3)*u[3]
end

u0 = [1.0;0.0;0.0]
tspan = (0.0,100.0)
prob = ODEProblem(lorenz,u0,tspan)
sol = solve(prob)
using Plots; plot(sol)

So this plots the u[1],u[2] and u[3] on the same graph, however I wanted to know how I could plot 3 individual graphs for u[1], u[2] and u[3]? This isn't useful here, but for mathematical differential equations, it would be useful to plot the component properties on different graphs.


Solution

  • The plotting commands are documented on this page. You can see that vars allows you to choose the variables you wish to plot. So to make some subplots, you can do things like:

    p1 = plot(sol, vars=1)
    p2 = plot(sol, vars=2)
    p3 = plot(sol, vars=3)
    plot(p1,p2,p3,layout=(3,1))
    

    If you want to plot all of the variables, a nice little trick described by @hesham_EE is you can just give a layout and it will automatically split it into different plots:

    plot(sol, layout = (3,1))