Quechua
Quechua

Reputation: 164

ggplot2 - Plot ymin and ymax as lines in stat_smooth

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.

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

Upvotes: 0

Views: 1634

Answers (1)

Adam Quek
Adam Quek

Reputation: 7163

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

Upvotes: 1

Related Questions