1

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? enter image description here

3
  • 2
    I'll get faster (and better) answers if you add some reproducible code. Commented Sep 26, 2018 at 18:14
  • Why do you want to keep the limits as are, if results can't go below zero? Commented Sep 26, 2018 at 18:28
  • 2
    Maybe you need a different model rather than a different plotting approach? It seems like you want a model that would force the CI to have 0 as a lower limit instead of the one you have. As an example (and leaving out many details), if you are using a linear model (assuming normality of errors) maybe you want the log link instead of the identity link. Commented Sep 26, 2018 at 18:57

2 Answers 2

3

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) ) 

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

You can use this option for y-axis (and similarly for x-axis):

scale_y_continuous(limits = c(min_y,max_y), oob=squish) 

Comments