Drawing only boundaries of stat_smooth in ggplot2

心已入冬 提交于 2019-12-05 05:13:27
agstudy

You can also use geom_ribbon with fill = 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) 

...and if for some reason you don't want the vertical bars, you can just use two geom_line layers:

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

There are most likely easier ways, but you may try this as a start. I grab data for the confidence interval with ggbuild, which I then use in 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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!