繁体   English   中英

如何使ggplot2在同一图中绘制多个模拟轨迹?

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

我想使用ggplot2从同一图上的任何分布(在当前情况下为对数正态)绘制多个模拟路径吗?

在for循环中使用print(ggplot())不会同时显示所有路径。

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

现在我想(说)在同一块情节中有100条这样的路径。

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())
} 

上面的循环显然无法完成这项工作。 有什么方法可以使用带有ggplot的简单R可视化此类模拟?

不必迭代地添加每行,而是可以迭代地在循环中进行仿真,将所有结果收集在data.frame中,然后一次绘制所有行。

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()

reprex软件包 (v0.3.0)创建于2019-08-13

在ggplot中,一种实现这种方法的方法是在每次迭代时在图上添加额外的图层。 这样做,只需更改后面的代码即可。

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)

请注意我如何启动绘图,类似于我在循环之前如何启动包含数据帧的列表。 循环然后逐步构建绘图,但是在for循环之后打印绘图之前,它是不可见的。 在这一点上,对每一层进行评估(因此,它可能比标准R图花费更长的时间。)

另外,由于我想为每行指定颜色,因此必须将col参数移到aes之外。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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