R:在ggplot中按2个因子变量分层

R: stratify by 2 factor variables in ggplot

library(ggplot2)
iris$Sepal.Length2 <- ifelse(iris$Sepal.Length < 5, 1, 0)
iris$Sepal.Width2 <- ifelse(iris$Sepal.Width < 3, 1, 0)

SmallLength <- data.frame(Petal.Length = iris$Petal.Length[iris$Sepal.Length2 == 1],
                         status = "Small Length")
LargeLength <- data.frame(Petal.Length = iris$Petal.Length[iris$Sepal.Length2 == 0],
                         status = "Large Length")
SmallWidth <- data.frame(Petal.Length = iris$Petal.Length[iris$Sepal.Width2 == 1],
                         status = "Small Width")
LargeWidth <- data.frame(Petal.Length = iris$Petal.Length[iris$Sepal.Width2 == 0],
                         status = "Large Width")

Length <- rbind(SmallLength, LargeLength)
Width <- rbind(SmallWidth, LargeWidth)
ggplot(Length, aes(Petal.Length, fill = status)) + geom_density(alpha = 0.2) + labs(x = "Petal Length")

我有一个连续变量 Petal.Length,我想按 Sepal.LengthSepal.Width 对它进行分层,我已将这两个变量编码为二进制变量。在上图中,我仅按 Sepal.LengthPetal.Length 进行了分层。如何通过 Sepal.Width 进一步分层?结果图可能应该有 4 种颜色我认为......1 种颜色 Petal.Length 具有小长度和小宽度,1 种用于小长度和大宽度,1 种用于大长度和小宽度,1 种用于大长度和大宽度。

完成此操作的一种方法是将您想要对图表进行分层的变量放置在 geom_density 层中,如下所示:

ggplot(data = df, aes(x = , y = ) +
  geom_line(aes(color = factored_variable))

更多详情:Plotting two variables as lines using ggplot2 on the same graph

无需为此创建单独的数据框,您可以使用完整的 iris 数据集实现所需的一切:

iris$length_binary <- ifelse(iris$Sepal.Length < 5, "Small", "Large")
iris$width_binary <- ifelse(iris$Sepal.Width < 3, "Small", "Large")
iris$length_width = interaction(iris$length_binary, iris$width_binary, sep=", ")

ggplot(iris, aes(Petal.Length, fill = length_width)) + 
    geom_density(alpha = 0.2) + 
    labs(x = "Petal Length",
         fill = "Length, Width")

结果:

这是一个使用管道的示例 - 按原样使用您的数据,您需要绑定长度和重量 data.frames。

library(tidyverse)
iris %>% 
   mutate(statusl = factor(ifelse(Sepal.Length<5,'Small length', 'Large length')),
          statusw = factor(ifelse(Sepal.Width<3,'Small width', 'Large width')))  %>% 
   ggplot(aes(Petal.Length, fill=interaction(statusl, statusw))) + 
         geom_density(alpha = 0.2) + xlab("Petal Length")