使用ggplot和dplyr绘制多个组时出错

时间:2018-03-19 13:13:41

标签: r ggplot2 dplyr

示例数据:

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

我试图分别在所有年份的每个月绘制y和x。

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

我试图为此做一个dplyr解决方案:

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

为什么会出现这个错误?以及如何在一个页面中显示所有图表?

修改 我认为如果低估,有关人员应该说明为什么它被低估并且https://stackoverflow.com/help/how-to-ask的哪个方面没有得到满足。

1 个答案:

答案 0 :(得分:0)

我不确定“所有年份中每个月分别”是什么意思。但这是我的解释

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