在ggplot2中仅绘制stat_smooth的边界

7 plot regression r ggplot2

使用stat_smooth()geom_point有没有办法去除阴影拟合区域,但只绘制其外边界?我知道我可以删除阴影区域,例如:

 geom_point(aes(x=x, y=y)) + geom_stat(aes(x=x, y=y), alpha=0)
Run Code Online (Sandbox Code Playgroud)

但是我怎样才能使它的外边界(外部曲线)仍然可见为微弱的黑线?

ags*_*udy 11

您还可以使用geom_ribbonfill= NA.

gg <- ggplot(mtcars, aes(qsec, wt))+
        geom_point() +  
        stat_smooth( alpha=0,method='loess')

rib_data <- ggplot_build(gg)$data[[2]]

ggplot(mtcars)+
  stat_smooth(aes(qsec, wt), alpha=0,method='loess')+
  geom_point(aes(qsec, wt)) +  
  geom_ribbon(data=rib_data,aes(x=x,ymin=ymin,ymax=ymax,col='blue'),
                fill=NA,linetype=1) 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

...如果由于某种原因你不想要竖条,你可以只使用geom_line两层:

ggplot(mtcars)+
    stat_smooth(aes(qsec, wt), alpha=0,method='loess')+
    geom_point(aes(qsec, wt)) + 
    geom_line(data = rib_data,aes(x = x,y = ymax)) + 
    geom_line(data = rib_data,aes(x = x,y = ymin))
Run Code Online (Sandbox Code Playgroud)


Hen*_*rik 9

最有可能的方法很简单,但您可以尝试这样做.我抓住了置信区间的数据ggbuild,然后我用它geom_line

# create a ggplot object with a linear smoother and a CI
library(ggplot2)    
gg <- ggplot(data = mtcars, aes(x = wt, y = mpg)) +
    geom_point() +
    geom_smooth(method = "lm")
gg

# grab the data from the plot object
gg_data <- ggplot_build(gg)
str(gg_data)
head(gg_data$data[[2]])
gg2 <- gg_data$data[[2]]

# plot with 'CI-lines' and the shaded confidence area
ggplot(data = mtcars, aes(x = wt, y = mpg)) +
    geom_point() +
    geom_smooth(method = "lm", se = TRUE, size = 1) +
    geom_line(data = gg2, aes(x = x, y = ymin), size = 0.02) +
    geom_line(data = gg2, aes(x = x, y = ymax), size = 0.02)


# plot with 'CI-lines' but without confidence area
ggplot(data = mtcars, aes(x = wt, y = mpg)) +
    geom_point() +
    geom_smooth(method = "lm", se = FALSE, size = 1) +
    geom_line(data = gg2, aes(x = x, y = ymin), size = 0.02) +
    geom_line(data = gg2, aes(x = x, y = ymax), size = 0.02)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述