I'm trying to subset some dates into season then combine monthly plots of 'date and amplitude' for each season.
head(dat)
Date Amplitude
1 2009-09-13 -2.6966667
2 2009-09-14 -0.7264583
3 2009-09-15 -2.1823333
Here's my code to create seasons and YearMonth for plot titles:
x <- as.Date(dat$Date, format="%Y/%m/%d")
x <- as.Date(x, origin="2009-09-13")
x <- cut(x, breaks="quarter")
labs <- paste(substr(levels(x),1,4),"/",1:4, sep="")
dat$DateQ <- factor(x, labels=labs)
dat$YearMonth <- format(dat$Date, "%Y/%m")
head(dat)
Date Amplitude DateQ YearMonth
1 2009-09-13 -2.6966667 2009/1 2009/09
2 2009-09-14 -0.7264583 2009/1 2009/09
I used a split to create data frames for each season and then named the data frames with a for loop
dat_split_season <- split(dat, dat$DateQ)
new_names <- c("Summer_2009", "Fall_2009", "Winter_2010", "Spring_2010",
"Summer_2010", "Fall_2010", "Winter_2011",
"Spring_2011", "Summer_2011", "Fall_2011",
"Winter_2012", "Spring_2012", "Summer_2012")
for (i in 1:length(dat_split_season)) {
assign(new_names[i], dat_split_season[[i]])
}
I can create the desired monthly plots by season manually by changing df
df <- Winter_2012
graphs <- lapply(split(df,df$YearMonth),
function(gg) ggplot(gg, aes(x=Date, y=Amplitude)) +
geom_point() + geom_line() + ylim(-10, 10) +
ggtitle(paste(gg$YearMonth)) + theme_bw())
do.call("grid.arrange", graphs)
I would like to use a for loop or the apply() family to sequence through the seasons list, selecting the Date and Amplitude columns for each data frame and plotting by 'YearMonth'.
The issue I'm having is probably syntax related; I'm new to R and programming in general. But I have spent the last few days scouring the forum and I would appreciate some direction at this point. Thanks!
ggplotcall isn't working correctly?