15

I'm refering to this SO question from 2 years ago, with ggplot : Adjust Transparency (alpha) of stat_smooth lines, not just transparency of Confidence Interval

The first method suggested allows to set the alpha transparency of the confidence interval alone:

ggplot(head(airquality, 60), aes(x=Day, y=Temp, color=factor(Month))) +
  geom_point() + stat_smooth(method = "lm", se=TRUE, alpha=1.0)

enter image description here

The second method allows to set the alpha transparency for the line itself, but you loose the confidence interval in the meantime, even with se=TRUE:

ggplot(head(airquality, 60), aes(x=Day, y=Temp, color=factor(Month))) +
  geom_point() + geom_line(stat='smooth', method = "lm", se=TRUE, alpha=0.3)

enter image description here

My question: How to control the transparency of both the smoothing line and the confidence interval?

Community
  • 1
  • 1
agenis
  • 8,069
  • 5
  • 53
  • 102

2 Answers2

16

This calculates the model twice. But normally that shouldn't be a performance issue.

ggplot(head(airquality, 60), aes(x=Day, y=Temp, color=factor(Month))) +
  geom_point() + 
  geom_ribbon(stat='smooth', method = "lm", se=TRUE, alpha=0.1, 
              aes(color = NULL, group = factor(Month))) +
  geom_line(stat='smooth', method = "lm", alpha=0.3)

resulting plot

Roland
  • 127,288
  • 10
  • 191
  • 288
0

This is the easiest way I know how to do this. I'm sure you could also use it with a scale_color_manual as well if you have more specific color scales in mind.

ggplot(head(airquality, 60), aes(x=Day, y=Temp, 
                                 color=factor(Month))) +
  geom_point() + 
  geom_smooth(alpha=0.2) + #toggle this alpha for error bar opacity
  scale_color_viridis(discrete=TRUE, alpha = 0.9) + #toggle this alpha for line opacity 
  theme_minimal()

Open to questions, comments, or improvements.