Xia.Song
Xia.Song

Reputation: 426

Multiple acf plot in one ggplot.

I plot two acf in R with follow code, how can make the same plot in ggplot, I try to use geom_area,but I could not get same one.

data1 <- seq(1, 3000, 3)
data2 <- seq(1, 1000, 0.5)
acf(data2, plot = T, lag.max = 300,col=2,ylim=c(0,1))
par(new=TRUE)
acf(data1, plot = T, lag.max = 300,col=1,ylim=c(0,1))

enter image description here

Upvotes: 1

Views: 958

Answers (1)

PKumar
PKumar

Reputation: 11128

You can try below approach,

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 with area

ggplot(data=data[data$variable=="data2",], aes(x = lag, y = value, 
             fill = variable)) + geom_area(position = "dodge") +
  geom_area(data=data[data$variable=="data1",],
           aes(x = lag, y = value, fill=variable), position = "dodge")

GGPLOT with bar

ggplot(data=data[data$variable=="data2",], aes(x = lag, y = value, 
                                               fill = variable)) + geom_col(position = "dodge") +
  geom_col(data=data[data$variable=="data1",],
            aes(x = lag, y = value, fill=variable), position = "dodge")

You have below graphs from both the approaches

enter image description here:

Upvotes: 1

Related Questions