R 如何让ggplot2在同一个绘图中绘制多个模拟轨迹?
我想使用ggplot2从同一绘图上的任何分布(在本例中为对数正态分布)绘制多条模拟路径 在for循环中使用print(ggplot())不会同时显示所有路径R 如何让ggplot2在同一个绘图中绘制多个模拟轨迹?,r,ggplot2,R,Ggplot2,我想使用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)) #
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
库(ggplot2)
t在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)
库(ggplot2)
nsim您可以在循环中迭代模拟,在data.frame中收集所有结果,并一次绘制所有线,而不是迭代地添加每条线
库(ggplot2)
nsim
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)