R/loadingsPlot.R

Defines functions loadingsPlot

Documented in loadingsPlot

#' Plot coefficients from a linear (or other) model.
#'
#' This code was written by:
#' Carlisle Rainey
#' June 29, 2012
#' http://www.carlislerainey.com/
#'
#' ...and adapted/modified by Adam Duncan 2015. Any errors are strictly my own.
#'
#' Plots a nice looking coefficient plot that makes it easy to visualize
#' factor loadings.
#'
#' @param model a model object of the type generated by lm().
#' @param var.names a vector of variable names.
#'
#' @return a plot of the coefficients of the model.
#'
#' @examples
#' #Fill this in....
#'
#' @export
loadingsPlot <- function(model, var.names){
  # make a plot of the factor loadings.
  
  m <- model
  
  par(
    family = "serif",  # I don't plot in anything but serif
    oma = c(0,0,0,0),  # Since it is a single plot, I set the outer margins to zero.
    mar = c(5,10,4,2)  # Inner margins are set through a little trial and error.
  )
  # create an empty plot for total customization
  plot(NULL,                              # create empty plot
       xlim = c(-2, 2),                      # set xlim by guessing
       ylim = c(.7, length(var.names) + .3), # set ylim by the number of variables
       axes = F, xlab = NA, ylab = NA)       # turn off axes and labels

  # add the data
  # conveniently store the estimates (minus the constant)
  est <- coef(m)[-1]
  # conveniently store the std. errors (minus the constant)
  se <- sqrt(diag(vcov(m)))[-1]
  # loop over a counter the length of the estimate vector
  for (i in 1:length(est)) {
    # add the 90% confidence intervals
    lines(c(est[i] + 1.64*se[i], est[i] - 1.64*se[i]), c(i, i), 
          col ="light green", lwd = 8, lend = 2)
    # add the 50% confidence intervals
    lines(c(est[i] + .67*se[i], est[i] - .67*se[i]), c(i, i), lwd = 8,
          col = "dark grey", lend = 2)
    # add the points to the plot
    points(est[i], i, pch = 19, cex = 1, col = "black")
    # add the variable names
    text(-2.9, i, var.names[i], xpd = T, cex = .8)
  }
  # add axes and labels
  # add bottom axis
  axis(side = 1)
  # add verticle line
  abline(v = 0, lty = 3, col = "grey")
  # label bottom axis
  mtext(side = 1, "Linear Regression Coefficient", line = 3)
  # add title
  mtext(side = 3, "Factor Loadings: 50% and 90% Confidence Intervals", line = 1)
  # add lines around the plot
  box()
}
gtog/dMisc documentation built on May 17, 2019, 8:57 a.m.