Question

I have a data frame which consists from 3 columns: time, A, B. I managed to plot (A and B) VS time in one graph. I'd like to calculate the moving average for A, B and plot it on the same graph. I found similar question, however, it's for single data. I have followed the same steps but I couldn't combine the moving average of A and B on the same graph to make it for multiple.

Sample of my dataframe:

time,A,B
0.122096,1,0
0.207928,9,0
0.300415,17,30
0.400383,30,60
0.503295,26,50
0.606207,24,70
1.05641,7,50
1.066232,1,56
1.068054,1,60
1.072752,1,76
1.107066,5,30
1.209493,16,40
1.301466,33,50

My code:

require(reshape2)
require(ggplot2)
library(zoo)
df<-read.csv("DATA.csv")
temp.zoo<-zoo(df$time,df$A)
temp2.zoo<-zoo(df$time,df$B)

m.av<-rollmean(temp.zoo,10)
df$A.av=coredata(m.av)

m2.av<-rollmean(temp2.zoo,10)
df$B.av=coredata(m2.av)

p<-ggplot(dat = melt(df, id.var="time"), aes(x=time, y=value, color = variable)) + 
geom_line(size=0.6) +
// the above line is graphing the two columns(A and B ) VS time .
geom_line(aes(x=df$time,y=df$A.av),color="black") +
geom_line(aes(x=df$time,y=df$B.av),color="grey") 
print(p)

Don't know what I'm missing? Any suggestion?

Was it helpful?

Solution

First problem - in the zoo() function time and A should be placed in opposite order.

temp.zoo<-zoo(df$A,df$time)
temp2.zoo<-zoo(df$B,df$time)

Next, for rollmean() function you should add argument fill=list(NA,NULL,NA) to fill start and end with NA values to get the same length vector as original data.

m.av<-rollmean(temp.zoo,10,fill=list(NA,NULL,NA))
df$A.av=coredata(m.av)

m2.av<-rollmean(temp2.zoo,10,fill=list(NA,NULL,NA))
df$B.av=coredata(m2.av)

Now you can melt the original data frame before plotting. So for plotting you will need only one geom_line() call.

df.long<-melt(df, id.vars="time")

ggplot(data=df.long, aes(time,value,color=variable))+geom_line()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top