小编Nic*_*aev的帖子

ggplot 中带有 facet 的变量 hline

以 Iris 数据集为例,我可以生成一个带有 facet 的 ggplot。 ggplot 与 facet 代码是:

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 命令中?

r facet ggplot2

4
推荐指数
1
解决办法
3316
查看次数

标签 统计

facet ×1

ggplot2 ×1

r ×1