Reputation:
The confidence intervals in my plot extend beyond zero making the y axis go below zero. Any way to adjust this in ggplot so the confidence intervals doesn't go below zero while keeping the y axis limits as is?
Upvotes: 1
Views: 1105
Reputation: 97
You can use this option for y-axis (and similarly for x-axis):
scale_y_continuous(limits = c(min_y,max_y), oob=squish)
Upvotes: 0
Reputation: 9705
Use geom_ribbon
:
Example data:
set.seed(1)
df <- data.frame(x = 1:100, y = pmax(0, 35 - 1:100 * runif(100) ))
fit <- lm(y ~ x, data=df)
pred_df <- data.frame(x=df$x, predict(fit, interval="confidence"))
ggplot() + geom_point(aes(x=x, y=y), data=df) +
geom_ribbon(aes(x=x, ymin=pmax(0,lwr), ymax=upr), alpha=0.5, data=pred_df) + scale_y_continuous(limits=c(min(pred_df$lwr), NA) )
Upvotes: 3