簡體   English   中英

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對其進行分層,我都將其編碼為二進制變量。 在上面的情節中,我Petal.LengthSepal.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")

結果:

在此處輸入圖片說明

這是一個使用管道的示例-按原樣使用數據,您將需要長度和重量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")

實現此目的的一種方法是將要分層圖表的變量放置在geom_density層中,如下所示:

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

詳細信息: 在同一張圖上使用ggplot2將兩個變量繪制為線

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM