首页 文章

调整stat_smooth行的透明度(alpha),而不仅仅是Confidence Interval的透明度

提问于
浏览
31

使用ggplot2的stat_smooth(),我很好奇如何调整生成的回归线的透明度 . 使用geom_points()或geom_line(),通常会为'alpha'设置一个值,表示透明度百分比 . 但是,使用stat_smooth(),alpha设置置信区间的透明度(在我的示例中,关闭 - se = FALSE) .

我似乎无法找到一种方法使回归线的透明度低于1 .

你的建议很棒 .

Sample Code

library(reshape2)
 df <- data.frame(x = 1:300)
 df$y1 <-  0.5*(1/df$x + 0.1*(df$x-1)/df$x + rnorm(300,0,0.015))
 df$y2 <-  0.5*(1/df$x + 0.3*(df$x-1)/df$x + rnorm(300,0,0.015))
 df$y3 <-  0.5*(1/df$x + 0.6*(df$x-1)/df$x + rnorm(300,0,0.015))
 df <- melt(df, id = 1)

 ggplot(df, aes(x=x, y=value, color=variable)) +
   geom_point(size=2) +
   stat_smooth(method = "lm", formula = y ~ 0 + I(1/x) + I((x-1)/x),
               se = FALSE,
               size = 1.5,
               alpha = 0.5)

enter image description here

2 回答

  • 48

    要为该行设置alpha值,您应该将 stat_smooth() 替换为 geom_line() ,然后在 geom_line() 内使用与 stat_smooth() 中相同的参数,并另外添加 stat="smooth" .

    ggplot(df, aes(x=x, y=value, color=variable)) +
      geom_point(size=2) +
      geom_line(stat="smooth",method = "lm", formula = y ~ 0 + I(1/x) + I((x-1)/x),
                  size = 1.5,
                  linetype ="dashed",
                  alpha = 0.5)
    

    enter image description here

  • 6

    作为一种更直观的替代方案 - 也许是从这个答案后创建的 - 您可以使用 stat_smooth (geom="line") . SE信封消失了,但你可以用以下内容添加回来:

    geom_smooth (alpha=0.3, size=0, span=0.5) stat_smooth (geom="line", alpha=0.3, size=3, span=0.5) +

    第一行创建SE . 没有(0宽度)线,第二行在其顶部添加线 . (当前)文档提到 stat_smooth 适用于非标准的geoms(例如"line") .

相关问题