在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)))