R/visualise_qqplot.R

#' @title Visualise a normal QQ-plot for a given vector
#' 
#' @description Plots a normal qq-plot for a given vector.
#' This function utilises ggplot2 to design and plot the Visualisation.
#' The plots can also be saved to a specified directory.
#' Original code by Aaron (2010) - https://stackoverflow.com/questions/4357031/qqnorm-and-qqline-in-ggplot2/
#' 
#' @param vector A vector to be visualise
#'  
#' @param directory A character object specifying the directory where the data frame is to be saved as a .csv file.
#'
#' @return Outputs a variety of bar charts or histograms
#' 
#' @import ggplot2
#' 
#' @export
#' 
#' @seealso \code{\link{visualise_residuals}}, \code{\link{visualise_variables_x}}, \code{\link{visualise_variables_xx}}
#' 
#' @examples 
#' # Example Data
#' x <- rnorm(n = 600, mean = 50, sd = 10)
#' mod <- lm(data = iris, Sepal.Length ~ .)
#' # Visualise the residuals of the model
#' visualise_qqplot(vector = x)
#' visualise_qqplot(vector = mod$residuals)
#' 
visualise_qqplot <- function(vector, 
                             directory = NULL) 
  {
  
  # save the name of the vector
  vname <- deparse(substitute(vector))
  
  # following four lines from base R's qqline()
  y <- quantile(vector[!is.na(vector)], c(0.25, 0.75))
  
  # calculate the norm quantiles
  x <- qnorm(c(0.25, 0.75))
  
  # calculate the slope of the plot
  slope <- diff(y)/diff(x)
  
  # calculate the intercept of the plot
  intercept <- y[1L] - slope * x[1L]
  
  # turn the vector into a one-dimensional data frame
  dataset <- data.frame(resids = vector)
  
  # save the ggplot
  qqplot <- ggplot(data = dataset, 
                   mapping = aes(sample = resids)) + 
            stat_qq() + 
            # add the normality line
            geom_abline(slope = slope, 
                        intercept = intercept,
                        colour = "red",
                        size = 1) +
            # Add labels to the plot
            labs(title = paste("QQplot of", vname, sep = " "),
                 x = "Theoretical",
                 y = "Observed") +
            # add a minimal theme to the plot
            theme_minimal()
  
  # print the qqplot
  print(qqplot)
  
  # write the qqplot to a specified directory
  if(!is.null(directory)) {
    
    ggsave(filename = paste("QQplot_of_", "vname", ".pdf", sep = ""), 
           path = directory,
           device = "pdf",
           width = 8, 
           height = 6, 
           units = c("in"))
    
  }
  
}
oislen/BuenaVista documentation built on May 16, 2019, 8:12 p.m.