3

I am using alpha to set transparency for the smoothing line in ggplot but instead I get transparency only in the Error band that surrounds the fitted line.

My code is the following:

z1 <- rnorm(10)

z2 <- z1 ^ 2

error <- rnorm(10, 0.25)

y <- 1 + 0.5 * z1 + error

data1 <- data.table(y, z1, z2)

ggplot(data1) +
  geom_point(aes(x = z1, y = y), color = "blue", size = 3) +
  geom_point(aes(x = z2, y = y), color = "red", size = 3) +
  geom_smooth(method = lm, aes(x = z1, y = y), color = "blue", size = 2, alpha = 0.1) +
  geom_smooth(method = lm, aes(x = z2, y = y), color = "red", size = 2, alpha = 0.1) 

The output is this: enter image description here

How can I set explicitly the transparency of the regression line as well?

Your advice will be appreciated.

rf7
  • 1,993
  • 4
  • 21
  • 35
  • 1
    @Jaap, I don't know the protocol on linking to external sites, but there is a really good answer to this question on google groups (but not on SO). The link is https://groups.google.com/forum/#!topic/ggplot2/mE__po966-k. It might be worthwhile to include it as an answer for future SO readers, but again I don't know if that is frowned upon in SO. – Mike H. Jun 11 '17 at 14:50

1 Answers1

9

You can use geom_line for more fine-grained control of the regression line.


ggplot(data1) +
  geom_point(aes(x = z1, y = y), color = "blue", size = 3) +
  geom_point(aes(x = z2, y = y), color = "red", size = 3) +
  geom_line(stat = "smooth", method = lm, aes(x = z1, y = y), color = "blue", size = 2, alpha = 0.1) +
  geom_line(stat = "smooth", method = lm, aes(x = z2, y = y), color = "red", size = 2, alpha = 0.1) +
  geom_smooth(method = lm, aes(x = z1, y = y), color = NA, size = 2, alpha = 0.1) +
  geom_smooth(method = lm, aes(x = z2, y = y), color = NA, size = 2, alpha = 0.1) 

yeedle
  • 4,918
  • 1
  • 22
  • 22