使用ggplot以两种不同方式分组

时间:2019-06-28 17:18:20

标签: r ggplot2 dplyr

我有一些看起来像这样的数据:

id = rep(1:33,3)
year = rep(1:3,33)
group = sample(c(1:3),99, replace=T)
test_result = sample(c(TRUE,FALSE), size=99, replace = T)


df = data.frame(id, year, group, test_result)
df$year = as.factor(year)
df$group = as.factor(group)

我的目标是对其进行可视化,以便查看组号和年份与test_result的关系。

df %>% 
    group_by(id,year) %>% 
    summarize(x=sum(test_result)) %>%
ggplot() + 
    geom_histogram(aes(fill = year, 
                       x = x), 
                   binwidth = 1, 
                   position='dodge') + 
    theme_minimal()

enter image description here

几乎使我到那里。我想要的是能够在此末尾添加facet_wrap(group~.)之类的内容,以显示这些变化如何按组进行更改,但显然group不在聚合数据帧中。

目前,我最好的解决方案是显示

之类的多个图
df %>% filter(group==1) # Replace group number here
    group_by(id,year) %>% 
    summarize(x=sum(test_result)) %>%
ggplot() + 
    geom_histogram(aes(fill = year, 
                       x = x), 
                   binwidth = 1, 
                   position='dodge') + 
    theme_minimal()

但是我很想弄清楚如何将它们全部放在一个图中,我想知道这样做的方法是否就是将更多的分组逻辑放入ggplot中?

0 个答案:

没有答案