Ordinary differential equations: Slope field and solution curves with R
Drawing a slope field of an autonomous ODE with the flowField function
Suppose we have an autonomus differential equation of the form for a certain function and we want to draw the slope field using R. At each point we can then calculate the slope of a solution and draw in the -plane a short line segment with this slope. To do this on a regular grid, the function flowField
from the phaseR
package is useful. There are no facilities for non-autonomous differential equations; then you must create your own code for a line element field.
Using flowField for the slope field A concrete example with looks as follows:
library(phaseR)
model <- function(time, initialstate, parameters){
with(as.list(c(initialstate, parameters)), {
dydt <- 2-2*y
return(list(dydt))
})
}
params <- NULL
flowField(model, xlim = c(0, 2), ylim = c(0, 2),
parameters = params, system = "one.dim",
state.names = c("y"), add = FALSE,
xlab = "t", ylab = "y", points = 11,
arrow.head = 0.001, col = "red",
main = "slope field of dy/dt = 2 - 2y")
Unlock full access