Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having several fits in one plot (in R)

Tags:

r

ggplot2

I was wondering how I can modify the following code to have a plot something like enter image description here

    data(airquality)
    library(quantreg)
    library(ggplot2)
    library(data.table)
    library(devtools)


    # source Quantile LOESS
    source("https://www.r-statistics.com/wp-content/uploads/2010/04/Quantile.loess_.r.txt")    

 airquality2 <- na.omit(airquality[ , c(1, 4)])

    #'' quantreg::rq
    rq_fit <- rq(Ozone ~ Temp, 0.95, airquality2)
    rq_fit_df <- data.table(t(coef(rq_fit)))
    names(rq_fit_df) <- c("intercept", "slope")

    #'' quantreg::lprq
    lprq_fit <- lapply(1:3, function(bw){
      fit <- lprq(airquality2$Temp, airquality2$Ozone, h = bw, tau = 0.95)
      return(data.table(x = fit$xx, y = fit$fv, bw = paste0("bw=", bw), fit = "quantreg::lprq"))
    })

    #'' Quantile LOESS
    ql_fit <- Quantile.loess(airquality2$Ozone, jitter(airquality2$Temp), window.size = 10,
                             the.quant = .95,  window.alignment = c("center"))
    ql_fit_df <- data.table(x = ql_fit$x, y = ql_fit$y.loess, bw = "bw=1", fit = "Quantile LOESS")

I want to have all these fits in a plot.


1 Answers

geom_quantile can calculate quantiles using the rq method internally, so we don't need to create the rq_fit_df separately. However, the lprq and Quantile LOESS methods aren't available within geom_quantile, so I've used the data frames you provided and plotted them using geom_line.

In addition, to include the rq line in the color and linetype mappings and in the legend we add aes(colour="rq", linetype="rq") as a sort of "artificial" mapping inside geom_quantile.

library(dplyr) # For bind_rows()

ggplot(airquality2, aes(Temp, Ozone)) + 
  geom_point() +
  geom_quantile(quantiles=0.95, formula=y ~ x, aes(colour="rq", linetype="rq")) +
  geom_line(data=bind_rows(lprq_fit, ql_fit_df), 
            aes(x, y, colour=paste0(gsub("q.*:","",fit),": ", bw),
                linetype=paste0(gsub("q.*:","",fit),": ", bw))) +
  theme_bw() +
  scale_linetype_manual(values=c(2,4,5,1,1)) +
  labs(colour="Method", linetype="Method",
       title="Different methods of estimating the 95th percentile by quantile regression")

enter image description here

like image 197
eipi10 Avatar answered Nov 28 '25 15:11

eipi10