在 geom_smooth 阈值之外的 ggplot 中标记值

Al1*_*l14 4 r ggplot2

只有当它们在置信区间(geom_smooth 区域)之外时,我才想在 ggplot 中标记值。下面是我的示例,我可以在其中标记所有这些。

a <- sample(1:15)
b <- sample(-6:-20)
c <-sample(letters,15)
x1 <- data.frame(a, b, c)

gg <- ggplot(x1, aes(x = a, y = b)) + labs(x = "New x label", y= "New x label") + 
  geom_point()+ geom_smooth(method=lm) + geom_text(aes(label=c),hjust=2, vjust=1) 
Run Code Online (Sandbox Code Playgroud)

pic*_*ick 5

您可以在ggplot调用之前进行拟合,并为置信区域外的点创建一个带有标签的变量。

## Get fit, and make a variable with labels for points outside conf. interval
fit <- lm(b ~ a)
dat <- predict(fit, interval="confidence")
x1$inside <- ifelse(x1$b < dat[,"upr"] & x1$b > dat[,"lwr"], "", as.character(x1$c))

gg <- ggplot(x1, aes(x = a, y = b)) +
  labs(x = "New x label", y= "New x label") + 
  geom_point() +
  geom_smooth(method=lm) + geom_text(aes(label=inside),hjust=2, vjust=1)
gg
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

另一种选择是使用ggplot_build从中提取数据ggplot并使用它来确定应标记哪些点。

## Use this to get data about the curve
info <- ggplot_build(gg)[[1]][[2]]
Run Code Online (Sandbox Code Playgroud)