Reputation: 677
I have a data frame that contains monthly time series data (from jan 2010 through dec 2012).
df<- data.frame(code=NA,Year=NA,Month=rep(seq(as.Date('2010/1/1'),by='month',length.out=36),3),x1=rnorm(3*36))
df$code[1:36]<-1; df$code[37:72]<-2; df$code[73:108]<-3
yr <- c(rep(2010,12),rep(2011,12),rep(2012,12))
df$Year<-rep(yr,3)
I would like to extract the rows that have the same code (there will be 36 rows for each code), and plot the values for each code on top of each other. I tried achieving this by the following code:
m <- ggplot(df[1:36,], aes(x=Month,y=x1)) + geom_point() + geom_line(aes(color ='ID:1')) +
scale_x_date(labels = date_formatv(format = "%m"),breaks = date_breaks("month"))+
xlab("") + ylab("")+ facet_wrap(~Year,scales=("free_x"))
Now I wrote a for loop to extract the next 36 observations and add them to the plot:
for(i in 1:2){
data2 <- df[((i*36)+1):((i+1)*36),]
m<-m+geom_point(data=data2,aes(x=Month,y=x1))+geom_line(data=data2,aes(x=Month,y=x1
,color=paste0('ID:',i+1)))
}
This code produces the following plot:
Now my questions are:
(1) As you can see, I don't get a legend for ID:2 (it only produces the legend for the last one), how can I get that?
(2) I would like to see different color for each code (associated with the legend), how can I achieve that?
(3) I am sure there should be a better way to produce the desired output, rather than using for loop, which is not recommended, any suggestion?
Upvotes: 2
Views: 435
Reputation: 19867
Map code
to color
to your aes
statement.
m <- ggplot(df, aes(x=Month,y=x1,color=factor(code))) +
geom_point() +
geom_line() +
scale_x_date(labels = date_format(format = "%m"),breaks = date_breaks("month"))+
xlab("") + ylab("")+ facet_wrap(~Year,scales=("free_x"))
m
Upvotes: 1
Reputation: 78590
Instead of using a for loop or subsetting, add color = factor(code)
to your aesthetics, which will add separately colored lines (and points) for each group of 36:
m <- ggplot(df, aes(x=Month, y=x1, color = factor(code))) +
geom_point() + geom_line() +
scale_x_date(labels = date_format(format = "%m"),breaks = date_breaks("month"))+
xlab("") + ylab("")+ facet_wrap(~Year,scales=("free_x"))
print(m)
(You could naturally customize the label title with something like labs(color = "ID")
, or customize the choices of colors with scale_color_manual
).
Upvotes: 1