R/plot.R

Defines functions plot.linreg

Documented in plot.linreg

#' Plots two residual plots from a linreg object with LiU theme
#' @description \code{plot} plots the residuals vs fitted values and a scale-location plot for a linreg object with ggplot2 with LiU theme.
#' @param x A linreg object.
#' @param ... Further arguments passed to or from other methods.
#' @return Two ggplot objects: Residuals vs Fitted and Scale-Location.
#' @examples
#' plot(linreg(Petal.Length ~ Species, iris))
#' @export

plot.linreg <- function(x, ...){
  # The three largest residuals (absolute values)
  index <- order(abs(x$e_hat), decreasing = TRUE)[1:3]
  # First plot
  plot1 <- ggplot2::ggplot() + ggplot2::geom_point(ggplot2::aes(x = x$y_hat, y = x$e_hat)) + theme_liu() +
    ggplot2::geom_text(ggplot2::aes(x = x$y_hat[index], y = x$e_hat[index],
                  label = (1:nrow(x$data))[index]), nudge_x = 0.15) +
    ggplot2::geom_abline(slope = 0, linetype = "dotted", color = "grey") +
    ggplot2::labs(title = "Residuals vs Fitted", x = paste0("Fitted values\n", deparse(x$call_arg)),
         y = "Residuals") +
    ggplot2::theme(panel.grid = ggplot2::element_blank(),
          plot.title = ggplot2::element_text(hjust = 0.5)) +
    suppressWarnings(ggplot2::geom_smooth(ggplot2::aes(x = x$y_hat[-index], y = x$e_hat[-index]), method = "loess",
                se = FALSE, color = "red"))
  # Second plot
  plot2 <- ggplot2::ggplot() + ggplot2::geom_point(ggplot2::aes(x = x$y_hat, y = sqrt(abs(scale(x$e_hat))))) + theme_liu() +
    ggplot2::labs(title = "Scale-Location", x = paste0("Fitted values\n", deparse(x$call_arg)),
         y = expression(sqrt(abs("Standardized residuals")))) +
    ggplot2::theme(panel.grid = ggplot2::element_blank(),
          plot.title = ggplot2::element_text(hjust = 0.5)) +
    suppressWarnings(ggplot2::geom_smooth(ggplot2::aes(x = x$y_hat[-index], y = sqrt(abs(scale(x$e_hat)))[-index]), method = "loess",
                se = FALSE, color = "red")) +
    ggplot2::geom_text(ggplot2::aes(x = x$y_hat[index], y = sqrt(abs(scale(x$e_hat)))[index],
                  label = (1:nrow(x$data))[index]), nudge_x = 0.15)
  #plot(plot1)
  #par(ask = TRUE)
  #plot(plot2)
  suppressMessages(suppressWarnings(plot(plot1)))
  graphics::par(ask = TRUE)
  suppressMessages(suppressWarnings(plot(plot2)))
}
Sidryd/lab4sidjac documentation built on Oct. 17, 2020, 11:05 p.m.