0
votes

I'm plotting a linear regression line with ggplot2 using the stat_smooth function.

As expected, the function calculates the predicted value, the confidence intervals and the standard error, as written on the help page.

  • y: predicted value
  • ymin: lower pointwise confidence interval around the mean
  • ymax: upper pointwise confidence interval around the mean
  • se: standard error

The default method to plot 95% confidence interval is similar to the output of geom_ribbon.

I would like to plot ymin and ymax as lines, without the shaded grey area.

Is there a way to do it directly in the function? Do I have to directly access the values?

EDIT: the plot is a dotplot, the goal of the regression line is simply to visualize a trend. Therefore, I do not have a lm object. I could plot the output of a regression object, of course, but I was wondering if I could fully take advantage of the very convenient stat_smooth and manually set plotting parameters

1
In addition to the answer by @AdamQuek, you can use stat_smooth(method = "lm", se = F) + stat_smooth(method = "lm", geom = "ribbon", fill = NA, linetype = "dashed", colour = "black") as a work-around. However, there's no way to remove the "end caps" of the now-clear, outlined ribbon. - Brian
Thank you @Brian, that's exactly what I was looking for (but the "end caps"...). You may add it as an answer, I'll tick it - Quechua

1 Answers

1
votes

Here's an example using broom and ggplot2 on iris data-set:

fit <- lm(Petal.Length ~ Sepal.Length, iris)
newd <- augment(fit)

ggplot(newd, aes(x=Sepal.Length)) +
  geom_point(aes(y=Petal.Length)) +
  geom_line(aes(y=.fitted)) +
  geom_line(aes(y=.fitted + 1.96*.se.fit), colour="blue", linetype="dotted") + 
  geom_line(aes(y=.fitted - 1.96*.se.fit), colour="blue", linetype="dotted") 

enter image description here

The above is the equivalent of the stat_smoothmethod="lm") function:

ggplot(iris, aes(Sepal.Length, Petal.Length)) + 
     geom_point() + 
     stat_smooth(method="lm")

enter image description here