Skip to content

Instantly share code, notes, and snippets.

@abikoushi
Created May 2, 2026 11:13
Show Gist options
  • Select an option

  • Save abikoushi/c93cf740d9d88010307768a4577fcd2a to your computer and use it in GitHub Desktop.

Select an option

Save abikoushi/c93cf740d9d88010307768a4577fcd2a to your computer and use it in GitHub Desktop.
Numerical solution and slope field of logistic equation
library(deSolve)
library(ggplot2)
library(tidyr)
library(dplyr)
library(foreach)
library(patchwork)
mod_logistic <- function(Time, State, Pars) {
with(as.list(c(State, Pars)), {
dX <- a*X*(1.0 - X/N)
return(list(c(dX)))
})
}
pars <- c(a = 0.5, N=1)
ini <- c(X = 0.1)
times <- seq(0, 10, by = 0.1)
out <- ode(ini, times, mod_logistic, pars)
plot(out)
sol_ode_from_states <- function(df_state, times, func, parms){
res_df <- foreach(i=1:nrow(df_state), .packages='deSolve', .combine=rbind) %do% {
ode_out <- ode(y=c(unlist(df_state[i,,drop=FALSE])), times=times, func=func, parms=parms)
data.frame(group=i, ode_out)
}
return(res_df)
}
df_state <- data.frame(X = seq(-0.001, 1.2, length.out=12))
df_state
res <- sol_ode_from_states(df_state=df_state, times=times, func=mod_logistic, parms=pars)
p1 <- ggplot(res,aes(x=time, y=X, group=group))+
geom_line()+
theme_bw()
df_slope <- expand.grid(times=times, X=df_state$X) %>%
rowwise() %>%
mutate(slope=unlist(mod_logistic(times, c(X=X), pars))) %>%
ungroup() %>%
mutate(start=X, end = 0.25*slope+X) %>%
mutate(i = row_number()) %>%
pivot_longer(cols=c(start,end)) %>%
mutate(times=if_else(name=="end",times+0.25, times))
p2 <- ggplot(df_slope, aes(x=times, y=value, group=i))+
geom_path()+
theme_bw()
p <- p2/p1
ggsave(plot = p,filename = "logistic.png", width = 7, height = 6)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment