以 Iris 数据集为例,我可以生成一个带有 facet 的 ggplot。
代码是:
library(ggplot2)
data(iris)
y=iris
y$Petal.Width.Range=factor(ifelse(y$Petal.Width<1.3,"Narrow","Wide"))
y$Petal.Length.Range=factor(ifelse(y$Petal.Length<4.35,"Short","Long"))
ggplot(y, aes(Sepal.Length,Sepal.Width)) +
geom_point(alpha=0.5)+
geom_hline(yintercept =3 ,alpha=0.3)+
facet_grid(Petal.Width.Range ~ Petal.Length.Range)
Run Code Online (Sandbox Code Playgroud)
在这里,我在 4 种情况下的水平规格均为 3。如果我想要一个依赖于案例的规范,我该怎么办?例如,我可以定义 4 个不同的规范,如下所示:
y$threshold=2
y$threshold[(y$Petal.Width.Range=="Narrow")&(y$Petal.Length.Range=="Short")] =2
y$threshold[(y$Petal.Width.Range=="Narrow")&(y$Petal.Length.Range=="Long")] =2.5
y$threshold[(y$Petal.Width.Range=="Wide")&(y$Petal.Length.Range=="Short")] =3.1
y$threshold[(y$Petal.Width.Range=="Wide")&(y$Petal.Length.Range=="Long")] =4
Run Code Online (Sandbox Code Playgroud)
我应该如何将 y$threshold 添加到 ggplot 命令中?