如何仅显示 geom_smooth 预测的一部分?

Nev*_*iem 4 r ggplot2

我正在尝试绘制一个既涉及geom_point()函数又涉及函数的geom_smooth()图形。

我想geom_smooth()在某个 x 值处裁剪函数,但仅在其所有值都已用于计算平滑曲线之后(即我不想使用xlim(),这将删除用于绘图的值)。

可重现的例子:

library(dplyr)
library(ggplot2)
set.seed(42)
test <- data.frame(replicate(2,sample(0:10,100,rep=TRUE)))
g <- ggplot() + geom_point(data = test, aes(x = X1, y = X2))

t_i <- test
t_i$group <- as.factor(as.numeric(cut(t_i$X1, 25)))
summar_t <- t_i %>% 
   group_by(group) %>% 
   summarise(y_mean=mean(X2),
             y_sd=sd(X2),
             c_mean =mean(X1,na.rm=T),
             n =n()
             )
summar_t$t_2sd <- summar_t$y_mean + summar_t$y_sd*2

g2 <- g + geom_smooth(data = summar_t, aes(x=c_mean, y = t_2sd), se=FALSE, method = lm, formula=y~poly(x,2), color = "black", linetype=3)
Run Code Online (Sandbox Code Playgroud)

当前图像 想要的图片

mar*_*kus 6

您可以使用xseq传递给的参数StatSmooth$compute_group,如下所示:

library(ggplot2)
ggplot(mtcars, aes(hp, mpg)) + 
  geom_point() +
  geom_smooth(se = FALSE) +
  geom_smooth(se = FALSE, xseq = 100:200, col = "red") 
Run Code Online (Sandbox Code Playgroud)

结果

在此处输入图片说明