user6121484
user6121484

Reputation: 143

add confidence interval to splines from quantile regression

I am using quantreg to fit a quantile regression and have also added some knots based on x-values (quantiles). I now would like to plot this and also have the confidence intervals. Not sure how to do that.

Here is a reproducible example:

  #create data    
  x <- seq(0,100,length.out = 100)        
  sig <- 0.1 + 0.05*x 
  b_0 <- 6                                
  b_1 <- 0.1                              
 set.seed(1)                             
 e <- rnorm(100,mean = 0, sd = sig)      
 y <- b_0 + b_1*x + e 

mydata <- data.frame(x,y, age=sample(30:70,100,replace=TRUE), sex=sample(c("Male","Female"),100, replace=TRUE))

#run regression
library(quantreg)
library(splines)
model <- rq(y ~ ns(x, knots=c(25,50,75))+age+sex, tau=0.5, data=mydata ) 

#plot
sp <- c(25,50,75)
ggplot(mydata, aes(x=x,y=y))+ geom_point()+ geom_quantile(formula=y~ns(x,knots=sp), quantiles=0.5, se=T)

This does not show the confidence intervals?? Also, this plot does not take the covariates into account? Is there a way to do this?

Upvotes: 2

Views: 2310

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50668

You're not actually using results from your model in the plot. So I'm not entirely sure what you're trying to do.

You can use predict to get quantile regression model-based predictions including confidence intervals, and plot those with geom_ribbon:

# Get model-based predictions
pred <- as.data.frame(predict(model, data.frame(x = mydata$x, age = mydata$age, sex = mydata$sex), interval = "confidence"));
pred$x <- mydata$x;

#plot
sp <- c(25,50,75);
ggplot(mydata, aes(x=x,y=y)) +
    geom_point() +
    geom_line(data = pred, aes(x = x, y = fit)) +
    geom_ribbon(data = pred, aes(ymin = lower, ymax = higher, x = x), alpha = 0.4) +
    geom_quantile(formula = y ~ ns(x, knots = sp), quantiles = 0.5, se = T);

enter image description here

Upvotes: 3

Related Questions