R/plot_varpc.R

Defines functions plot_varpc

Documented in plot_varpc

#' Plot variables in the coordinate plane PC1-PC2.
#' 
#' This function plots the variables in the coordinate plane PC1-PC2.
#' 
#' @param mod A prcomp or princomp object.
#' @param ... Arguments to be passed to methods, such as graphical parameters (see par).
#' @examples
#' # For a prcomp object
#' pca1 <- prcomp(USArrests, scale = TRUE)  # Example
#' plot_varpc(pca1)
#' plot_varpc(pca1, main='Variables in PC1 and PC2',
#'            col='blue3', lwd=3)
#' #
#' # For a princomp object
#' pca2 <- princomp(x=USArrests, cor=TRUE)
#' plot_varpc(pca2, col='red', lwd=4)
#' 
#' @export
#' 
plot_varpc <- function(mod, col='gray60', ...) {
  stopifnot(class(mod) %in% c('prcomp', 'princomp'))
  if (class(mod) == 'prcomp') {
    x <- mod$rotation[, 1:2]
  } else {
    x <- mod$loadings[, 1:2]
  }
  n <- nrow(x)
  plot(NULL, xlim=c(-1, 1), ylim=c(-1, 1),
       xlab='PC1', ylab='PC2', las=1, ...)
  abline(h=0, col="gray30", lty='longdash')
  abline(v=0, col="gray30", lty='longdash')
  for (i in 1:n) arrows(0, 0, x[i, 1], x[i, 2], col=col, ...)
  text(x[, 1:2], cex=1, labels=rownames(x), adj=c(0, 0))
}
fhernanb/model documentation built on Sept. 16, 2017, 11 a.m.