gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:20:19 24 4
gpt4 key购买 nike

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

enter image description here

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

最佳答案

无需为此创建单独的数据框,您可以使用完整的 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")

结果:

enter image description here

关于R:在 ggplot 中按 2 个因子变量进行分层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43175142/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com