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

标签 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) 

最佳答案

您可以在 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

enter image description here

另一种选择是使用 ggplot_buildggplot 中提取数据并使用它来确定应该标记哪些点。
## 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/

相关文章:

r - Lua 替代 optim()

r - 使用 matlab 和 R 计算数据集的 PCA,但每个组件的方差不同

r - 多边形可以很好地裁剪不同缩放级别的ggplot2/ggmap

r - ggplot 条形图限制修复

r - 根据窗口大小动态调整 Shiny 图输出的高度和/或宽度

r - 如何根据另一列的值聚合两列的 R 数据框

r - 在 R 中构建嵌套列表

r - ggplotly 和 lubridate : Hoover shows seconds, 不是分钟

r - 使用 ggplot2 在 dplyr 链中设置子集/过滤器

r - 带有自定义字体的ggplot在shinyapps.io上没有正确显示