Home > Blockchain >  Add - 2 SE in regression line R
Add - 2 SE in regression line R

Time:11-15

I was wondering if it is possible to plot a regression line in R including - 2* Standard Error. For example, with iris :

library(ggplot2)
ggplot(iris, aes(x = Petal.Length, y = Sepal.Width)) geom_smooth(method=lm, color="black")  theme_bw()

the output is:

enter image description here

How would it possible (if possible) to expand the grey area for values twice the standard error?

CodePudding user response:

One option to achieve your desired result would be to manually add the confidence bands via stat_smooth and making use of after_stat:

library(ggplot2)
ggplot(iris, aes(x = Petal.Length, y = Sepal.Width))  
  geom_smooth(method = lm, color = "black", se = FALSE)  
  stat_smooth(aes(ymin = after_stat(y - 2 * se), ymax = after_stat(y   2 * se)), geom = "ribbon", method = lm, fill = "grey60", alpha = .4)  
  theme_bw()
#> `geom_smooth()` using formula 'y ~ x'
#> `geom_smooth()` using formula 'y ~ x'

  • Related