简体   繁体   中英

How to get ggplot2 to draw multiple simulated trajectories in same plot?

I want to draw multiple simulated paths from any distribution (lognormal in the present case) on the same plot using ggplot2?

Using print(ggplot()) inside a for- loop does not show the paths all together.

library(ggplot2)

t <- 1000  # length of a simulation    
time <- seq(0,t-1,by = 1) # make vector of time points
s <- cumsum(rlnorm(t, meanlog = 0, sdlog = 1))  # simulate trajectory of  lognormal variable
df <- data.frame(cbind(time,s)) # make dataframe
colnames(df) <- c("t","s")      # colnames
ggplot(df, aes(t,s )) + geom_line()  # Get one trajectory

Now i want (say) 100 such paths in the same plot;

nsim <- 100 # number of paths

for (i in seq(1,nsim, by =1)) {
s <- cumsum(rlnorm(t, meanlog = 0, sdlog = 1))
df <- data.frame(cbind(time,s))
colnames(df) <- c("t","s")
print(ggplot(df, aes(t,s, color = i)) + geom_line())
} 

The above loop obviously cannot do the job. Any way to visualize such simulations using simple R with ggplot?

Instead of adding each line iteratively, you could iteratively simulate in a loop, collect all results in a data.frame, and plot all lines at once.

library(ggplot2)

nsim <- 100
npoints <- 1000

sims <- lapply(seq_len(nsim), function(i) {
  data.frame(x = seq_len(npoints),
             y = cumsum(rlnorm(npoints, meanlog = 0, sdlog = 1)),
             iteration = i)
})
sims <- do.call(rbind, sims)

ggplot(sims, aes(x, y, colour = iteration, group = iteration)) +
  geom_line()

Created on 2019-08-13 by the reprex package (v0.3.0)

In ggplot one method to achieve such methods is to add extra layers to the plot at each iteration. Doing so, a simple change of the latter code should be sufficient.

library(ggplot2)
nsim <- 100 # number of paths
dat <- vector("list", nsim)
p <- ggplot()
t <- 1000  # length of a simulation    
time <- seq(0, t-1, by = 1)
for (i in seq(nsim)) {
    s <- cumsum(rlnorm(t, meanlog = 0, sdlog = 1))
    dat[[i]] <- data.frame(t = time, s = s)
    p <- p + geom_line(data = dat[[i]], mapping = aes(x = t, y = s), col = i)
} 
p #or print(p)

Note how I initiate the plot, similarly to how I initiate a list to contain the data frames prior to the loop. The loop then builds the plot step by step, but it is not visualized before i print the plot after the for loop. At which point every layer is evaluated (thus it can take a bit longer than standard R plots.)

Additionally as I want to specify the colour for each specific line, the col argument has to be moved outside the aes .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM