只有当它们在置信区间(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)
最佳答案
您可以在 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
另一种选择是使用
ggplot_build
从 ggplot
中提取数据并使用它来确定应该标记哪些点。## Use this to get data about the curve
info <- ggplot_build(gg)[[1]][[2]]
关于r - 在 geom_smooth 阈值之外的 ggplot 中标记值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31959961/