rggplot2dplyr

Error in plotting for multiple groups using ggplot and dplyr


Sample data:

dat <- data.frame(year = rep(2012:2015, each = 9), month = rep(4:12, times = 4), 
            y = runif(36), x = runif(36))

I am trying to plot y and x for each month across all years separately.

for(m in unique(dat$month)){
       test <- dat[dat$month == m,]
       ggplot(test, aes(x = x, y= y)) + geom_point()
     }

I tried to do a dplyr solution to this:

ggplot(dat %>% group_by(month) %>%  
                 aes(x = x, y = y, colour = factor(year))) +
    geom_point()

Error: ggplot2 doesn't know how to deal with data of class uneval

Why is this error? and how do I show all the plots in a single page?


Solution

  • I'm not really sure what "for each month across all years separately" means. But here's my interpretation

    library(ggplot2)
    
    dat <- data.frame(year = rep(2012:2015, each = 9), month = rep(4:12, times = 4), 
                      y = runif(36), x = runif(36))
    
    ggplot(dat, aes(x = x, y = y, color = factor(year))) + 
      geom_point() +
      facet_grid(year~month)
    

    enter image description here