Multiple ggAcf plot in R

2019-05-30 23:06发布

问题:

I have 2 time series data and I want to plot the ACF in one ggplot with different colour, I just found ggAcf, but it couldn't solve my problem

library(ggplot2)
data1<-seq(1,300,3)
data2<-seq(1,100,0.5)
ggAcf(data2,1)
ggAcf(data2,20)

I want to make the plot as follow type

How can I solve it?

回答1:

You can calculate the acf independently for each data set then add them to the same dataframe and plot from there

library(tidyr)
library(ggplot2)

data1 <- seq(1, 300, 3)
data2 <- seq(1, 100, 0.5)

acf1 <- acf(data1, plot = F, lag.max = 25)
acf2 <- acf(data2, plot = F, lag.max = 25)

acfs <- data.frame(lag = acf1$lag, acf1 = acf1$acf, acf2 = acf2$acf)

acfs %>% gather(key = data, value = acf, -lag) %>% ggplot(aes(x = lag, y = acf, 
  fill = data)) + geom_col(position = "dodge")



回答2:

library(ggplot2)
library(reshape2)
data1 <- seq(1, 300, 3)
data2 <- seq(1, 100, 0.5)
acf1 <- acf(data1, plot = F, lag.max = 25)
acf2 <- acf(data2, plot = F, lag.max = 25)
df<- data.frame(lag = acf1$lag,acf1=acf1$acf,acf2=acf2$acf)
colnames(df)<-c("lag","data1","data2")
data<-melt(df,id="lag")
ggplot(data, aes(x=lag, y=value)) +
   geom_area(aes(colour = variable, fill= variable), position = 'stack')