【问题标题】:Drawing only boundaries of stat_smooth in ggplot2在 ggplot2 中仅绘制 stat_smooth 的边界
【发布时间】:2013-08-12 14:30:16
【问题描述】:

当使用stat_smooth()geom_point 时,有没有办法移除阴影拟合区域,但只绘制其外部边界?我知道我可以通过以下方式移除阴影区域:

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

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

【问题讨论】:

  • 没有geom_stat。你的意思是stat_smooth
  • 按照OP,应该是c+stat_smooth(fill = "grey50", size = 2, alpha = 0)
  • stat_smoothgeom_smooth

标签: r plot ggplot2 regression


【解决方案1】:

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

...如果出于某种原因您不想要竖线,您可以只使用两个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))

【讨论】:

  • 希望您不介意编辑...只是将内容合并到最佳答案中。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    • 2017-10-02
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    相关资源
    最近更新 更多