59

Using ggplot2's stat_smooth(), I'm curious how one might adjust the transparency of the generated regression line. Using geom_points() or geom_line(), one normally sets a value for 'alpha', indicating the percent transparency. However, with stat_smooth(), alpha sets the transparency of the confidence interval (in my sample below, turned off - se=FALSE).

I cannot seem to find a way to make the regression line(s) a lower transparency than 1.

Your advice would be wonderful.

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

EconomiCurtis
  • 2,107
  • 4
  • 23
  • 33

2 Answers2

89

To set alpha value just for the line you should replace stat_smooth() with geom_line() and then inside the geom_line() use the same arguments as in stat_smooth() and additionally add 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

Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
  • 1
    Just a remark: with this method, the confidence interval has disapeared. I posted another question about this: http://stackoverflow.com/q/29235114/3871924 – agenis Mar 24 '15 at 15:06
  • @Didzis Elferts, are you aware of a better solution to this question? Any ggplot extension or improvement on this ? – Dan Aug 28 '17 at 02:53
  • Note to self: current (Nov 2018) default value of alpha for ``geom_smooth`` fill is ``alpha = 0.4`` – PatrickT Nov 24 '18 at 07:47
22

As an alternative that's slightly more intuitive -- perhaps created since this answer -- you can use stat_smooth (geom="line"). The SE envelope disappears, though you can add it back with something like:

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

The first line creates the SE. with no (0-width) line, and the second line adds the line over top of it. The (current) documentation mentions that stat_smooth is for non-standard geoms (e.g. "line").

Wayne
  • 933
  • 7
  • 11
  • 8
    Setting the **size=0** no longer makes the line disappear. Alternatively, you can use the parameter **linetype=0** to plot the standard error without the smooth line. – C W Oct 24 '17 at 19:21