Reputation: 1
I want to create a plot overlaying 1000 simulations of a MA(2) process (1 plot, 1000 lines). I cant seem to get ggplot to plot more than one of these 1000 series. There are many posts about this problem on here, and it seems that the problem for most is solved by using the melt function in the reshape2 library, however, this does not solve my problem. I am unsure what my problem is other than that other datasets/examples from here seem to work in plotting multiple lines, so I am wondering if it is the data my function is generating. Sorry if this is a simple fix, I just cant seem to find an answer.
#create function to simulate MA(2) process
sim<-function(n,sigma,mu,theta) {
epsilon<-rnorm(n,0,sigma)
z<-matrix(nrow=n,ncol=1001)
z<-replicate(1000,
z[,1]<-as.numeric(mu+epsilon[1:n]+theta*epsilon[2:n-1]) )
}
#run simulation, add time vector
z <-sim(23,0.5,0.61,0.95)
time<-matrix(seq(1,23))
z<-data.frame(time,z)
#collapse data
df <- data.frame(melt(zz, id.vars = 'time', variable.name = 'series'))
df[["series"]] <- gsub("X", "series", df[["series"]])
#attempt to plot using ggplot2's 'group' and 'color'
ggplot(data=df, aes(x=time,y=value, group=series)) +
geom_line(aes(color = series)) +
theme(legend.position='none')
Upvotes: 0
Views: 641
Reputation: 50738
It's not clear to me how you want to show 1000 lines in a single plot. This sounds like a bad idea. Furthermore, the code you're using to simulate random data from an MA(2) process doesn't work; why not use arima.sim
, which is there for exactly that purpose.
Here is an example plotting 10 random time series with data generated from an MA(2) process.
set.seed(2017);
replicate(10, arima.sim(model = list(ma = c(-.7, .1)), n = 100)) %>%
as_tibble() %>%
mutate(time = 1:n()) %>%
gather(key, val, -time) %>%
ggplot(aes(time, val, group = key)) +
geom_line(alpha = 0.4)
Upvotes: 2