在ggplot2中仅绘制stat_smooth的边界

时间:2013-08-10 23:36:30

标签: r plot ggplot2 regression

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

 geom_point(aes(x=x, y=y)) + geom_stat(aes(x=x, y=y), alpha=0)

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

2 个答案:

答案 0 :(得分:11)

您还可以geom_ribbon = NA使用fill

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) 

enter image description here

...如果由于某种原因你不想要垂直条,你可以只使用两个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))

答案 1 :(得分: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)

enter image description here