R/gglmplot.R

Defines functions gglmplot make_new_df

Documented in gglmplot

## create new data set based on the existing one
make_new_df <- function(df, var_names, n=100) {
  new.x <- seq(min(df[,"x"]), max(df[,"x"]), length.out=100)
  new.data <- data.frame(x=new.x)
  colnames(new.data) <- var_names[2]

  return(new.data)
}

#' Plot a linear regression model
#'
#' Plot a linear regression model using ggplot2
#'
#' Here come the details
#' @return A ggplot (object of class gg_plot)
#' @param model a linear model produced by lm()
#' @import stats ggplot2
#' @export
gglmplot <- function(model) {

  # extract the original data from the model
  df <- model$model
  var_names <- colnames(df)
  colnames(df) <- c("y", "x")

  # extract model properties
  intercept <- model$coefficients[1]
  slope <- model$coefficients[2]

  # calculate the intervals based on new data
  new.data <- make_new_df(df, var_names, 100)

  pred <- predict(model, newdata=new.data, interval = "p")
  conf <- predict(model, newdata=new.data, interval = "c")

  ## create a data frame with intervals for ggplot
  df_g <- cbind(new.data, pred[ , 2:3], conf[ , 2:3])
  colnames(df_g) <- c("x", "pred_low", "pred_upr", "conf_low", "conf_upr")
  df_g <- data.frame(df_g)

  ## make the ggplot
  p <- ggplot(data=df, aes(x=.data$x, y=.data$y)) +
    geom_point() +
    geom_abline(intercept=model$coefficients[1], slope=model$coefficients[2], col="red") +
    geom_line(data=df_g, mapping=aes(x=.data$x, y=.data$pred_low)) +
    geom_line(data=df_g, mapping=aes(x=.data$x, y=.data$pred_upr)) +
    geom_line(data=df_g, mapping=aes(x=.data$x, y=.data$conf_low)) +
    geom_line(data=df_g, mapping=aes(x=.data$x, y=.data$conf_upr))

  return(p)
}
january3/gglmplot documentation built on July 11, 2020, 12:33 a.m.