Minimalist
Minimalist

Reputation: 79

How to plot several curves on one graph with defined function in R?

I need to plot a couple of curves on one graph. I've got trajectories of Brownian simulation which I got from the function:

brownian <- function(T,N){
  alpha=0
  sigma=1
  
  delta_t=T/N
  
  t=seq(0,T,by=delta_t)
  #x=c(0,alpha*delta_t+sigma*sqrt(delta_t)*rnorm(N,mean=0,sd=1))
  x=c(0,alpha*delta_t+sqrt(delta_t)*rnorm(N,mean=0,sd=1))
  Xt=cumsum(x)
  plot(t,Xt,type='l',col = rep(1:3, each = 10),xlab="t=[0,T]",ylab = "B(t,ω)")
}

For example for brownian(1,1000) I get:

And for brownian(10,1000) I get:

As you can see I get black graphs. I have to plot these trajectories on one graph (every trajectory should have different color). When it takes several trajectories, it should look like:

Do you have any advices how can I plot these curves on one graph and each curve has different color?

Thanks in advance

Upvotes: 1

Views: 275

Answers (2)

Rui Barradas
Rui Barradas

Reputation: 76402

Here is a base R solution with matplot. It is ideal for this type of plot, since it computes the x and y axis ranges and plots all lines in one call only. It uses DaveArmstrong's idea of adding an extra argument ntimes. This argument is also used for the color scheme.

brownian <- function(T, N, ntimes){
  alpha <- 0
  sigma <- 1
  delta_t <- T/N
  t <- seq(0, T, by = delta_t)
  #x=c(0,alpha*delta_t+sigma*sqrt(delta_t)*rnorm(N,mean=0,sd=1))
  Xt <- replicate(ntimes,
                  cumsum(c(0, alpha*delta_t+sqrt(delta_t)*rnorm(N, mean = 0, sd = 1)))
  )
  matplot(t, Xt, 
          type = "l", lty = 1, 
          col = seq_len(ntimes),
          xlab = "t=[0,T]", ylab = "B(t,ω)")
}

set.seed(2020)
brownian(1, 1000, 5)

enter image description here

Upvotes: 0

DaveArmstrong
DaveArmstrong

Reputation: 21937

You could do this pretty easily by modifying the function and using ggplot() to make the graph. The function below takes ntimes as an argument which specifies the number of times you want to do the simulation. It then uses ggplot() to make the graph. You could adjust the internals of the function to have it produce a different looking plot if you like.

brownian <- function(T,N, ntimes){
  if((length(N) != length(T)) & length(N) != 1){
    stop("N has to be either length of T or 1\n")
  }
  alpha=0
  sigma=1
  if(length(N) == 1 & length(T) > 1)N <- rep(N, length(T))
  dat <- NULL
  for(i in 1:ntimes){
    delta_t=T/N  
    t=seq(0,T,by=delta_t)
    #x=c(0,alpha*delta_t+sigma*sqrt(delta_t)*rnorm(N,mean=0,sd=1))
    x=c(0,alpha*delta_t+sqrt(delta_t)*rnorm(N,mean=0,sd=1))
    Xt=cumsum(x)
    dat <- rbind(dat, data.frame(xt=Xt, t=t, n=i))
  }
  require(ggplot2)
  ggplot(dat, aes(x=t, y=xt, colour=as.factor(n))) + 
    geom_line(show.legend=FALSE) + 
    labs(x="t=[0,T]",y = "B(t,ω)", colour="T") + 
    theme_classic()
}
brownian(10,1000, 5)

enter image description here

Upvotes: 1

Related Questions