Search code examples
rplotodedesolve

Plotting multiple plots for different initial conditions in one graph


I am using the following code. How can I plot time (x-axis) vs C_WT (y-axis) line plots for different C_WT values as in vectorC_WT in a single graph in R ?

kon_WT = 1         
koff_WT = 10
R_WT =   20
Complex <- function (t,y,parms){
with(as.list(y), {

dC_WT <-  koff_WT*RL_WT -kon_WT*R_WT*C_WT 
dRL_WT <- kon_WT*R_WT*C_WT - koff_WT*RL_WT   #uM
dR_WT <-  koff_WT*RL_WT -kon_WT*R_WT*C_WT 

return(list(c(dC_WT, dRL_WT, dR_WT)))
})
}
resC_WT <- function(iC_WT) {
 times <- seq(0,1,0.01)
 Out <- ode(y = c(C_WT = iC_WT, RL_WT = 0, R_WT= R_WT), times = times, func=Complex, 
parms=NULL)
Output <- data.frame(Out)
}

vectorC_WT <- 1:11
sapply(vectorC_WT, FUN=resC_WT)
Complex1 <- as.data.frame(t(Complex1))

Solution

  • Here a simple solution, using lists and the built-in plotfunction of deSolve. It accepts one single run as first argument and a list of runs as its second argument.

    To make it work, remove the as.data.frame-conversion and use lapply instead of sapply.

    library(deSolve)
    
    kon_WT <- 1         
    koff_WT <- 10
    R_WT <-   20
    Complex <- function (t,y,parms){
      with(as.list(y), {
        
        dC_WT <-  koff_WT*RL_WT -kon_WT*R_WT*C_WT 
        dRL_WT <- kon_WT*R_WT*C_WT - koff_WT*RL_WT   #uM
        dR_WT <-  koff_WT*RL_WT -kon_WT*R_WT*C_WT 
        
        return(list(c(dC_WT, dRL_WT, dR_WT)))
      })
    }
    resC_WT <- function(iC_WT) {
      times <- seq(0,1,0.01)
      Out <- ode(y = c(C_WT = iC_WT, RL_WT = 0, R_WT= R_WT), times = times, func=Complex, 
                 parms=NULL)
      Out
    }
    
    vectorC_WT <- 1:11
    
    result <- lapply(vectorC_WT, FUN=resC_WT)
    
    plot(result[[1]], result)
    

    If you wish a plot of only a single state variable, use which:

    plot(result[[1]], result, which = "C_WT")
    

    multiple runs