7

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

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

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

4

2 回答 2

11

您也可以使用geom_ribbonwith 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) 

在此处输入图像描述

...如果由于某种原因你不想要竖线,你可以只使用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))
于 2013-08-11T01:25:57.720 回答
10

很可能有更简单的方法,但您可以先尝试一下。我使用 获取置信区间的数据,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)

在此处输入图像描述

于 2013-08-11T01:07:27.330 回答