以 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 命令中?
一个简单的解决办法就是你改变hline调用此:geom_hline(aes(yintercept=threshold), alpha=0.3) +。
问题是,这将在您的绘图上绘制 150 条线(150 是ydata.frame 中的行数)。也许这对你没问题,因为这些线大多会叠在一起,而你实际上只会在正确的位置看到四条线。
但是,这是我创建一个较小的辅助 data.frame 的另一种解决方案。这是 ggplot2 中的常用方法。请注意如何将新的 data.frame 指定为geom_hline调用中的数据源。
hline_dat = data.frame(Petal.Width.Range=c("Narrow", "Narrow", "Wide", "Wide"),
Petal.Length.Range=c("Short", "Long", "Short", "Long"),
threshold=c(2, 2.5, 3.1, 4))
p = ggplot(y, aes(Sepal.Length,Sepal.Width)) +
geom_point(alpha=0.5) +
geom_hline(data=hline_dat, aes(yintercept=threshold), colour="salmon") +
facet_grid(Petal.Width.Range ~ Petal.Length.Range)
ggsave("plot.png", plot=p, height=4, width=6)
Run Code Online (Sandbox Code Playgroud)