如何在ggplot2中按多个变量分组

时间:2020-02-28 16:08:31

标签: r ggplot2

在ggplot2中,aes()命令允许通过设置group =color =等来细分数据集。有没有一种方法可以对多个变量进行分组,类似于dplyr可以设置多个group_by命令吗?

例如,我想绘制“泰坦尼克号”数据集的密度,该数据集针对年龄被变量"Female""Survived"细分。 "Female""Survived"都是伪变量,因此我想以四种密度结尾。

直观地讲,我将c("Female", "Survived")传递给group内的aes()属性,如下面的代码所示。正确的方法是什么?

library("tidyverse")

titanic <- read_csv("https://stanford.io/2O9RUCF",
                    col_types = cols(
                      Survived = col_logical(),
                      Pclass = col_integer(),
                      Name = col_character(),
                      Sex = col_character(),
                      Age = col_double(),
                      `Siblings/Spouses Aboard` = col_integer(),
                      `Parents/Children Aboard` = col_integer(),
                      Fare = col_double()
                    ))

titanic <- titanic %>% 
  mutate(Female = (Sex == "Female")) %>% 
  dplyr::select(-Sex, -Name)


titanic %>% 
  ggplot() +
    geom_density(aes(Age, color = c(Female, Survived)))

0 个答案:

没有答案
相关问题