R/PLOT.r

Defines functions PLOT

Documented in PLOT

PLOT <- function(obj, 
                 classobj="",
                 map="symmetric", 
                 rescale=1, 
                 dim=c(1,2), 
                 axes.inv = c(1,1), 
                 main="", 
                 most = FALSE,
                 arrows = TRUE,
                 cols=c("blue","red"), 
                 colarrows = "pink", 
                 cexs=c(0.8,0.8), 
                 fonts=c(2,4), 
                 group=NA, 
                 groupnames=NA, 
                 groupcols=NA, 
                 grouppchs=NA, 
                 legendpos=NA, 
                 ellipse=NA,
                 ellipse.sup=FALSE,
                 conf=0.95,
                 labelrows=TRUE)   { 

  # 1. VALIDATE AND STANDARDIZE CLASS EXPECTATIONS
  valid_classes <- c("PCA", "LRA", "CA", "ca")
  current_class <- class(obj)
  
  if (!any(current_class %in% valid_classes)) {
    stop("Object not created by PCA, LRA, CA or ca, so generic PLOT cannot be used")
  }
  
  # Dynamically switch the display label based on the input object's class metadata
  if (classobj == "") {
    if (toupper(current_class) == "PCA") classobj <- "PCA"
    if (toupper(current_class) == "LRA") classobj <- "LRA"
    if (toupper(current_class) == "CA"  || current_class == "ca")  classobj <- "CA"
  }

  # 2. ELEMENT-WISE VECTOR MULTIPLICATION
  scaling_rpc <- obj$sv[dim] * axes.inv
  obj.rpc     <- t(t(obj$rowcoord[, dim, drop = FALSE]) * scaling_rpc)
  
  obj.csc     <- t(t(obj$colcoord[, dim, drop = FALSE]) * axes.inv)
  obj.cpc     <- t(t(obj.csc) * obj$sv[dim])
  obj.ccc     <- obj.csc * sqrt(obj$colmass)

  # 3. ASSIGN THE CORRESPONDING BI-PLOT MAP TYPE
  if (map == "symmetric")    obj.crd <- obj.cpc
  if (map == "asymmetric")   obj.crd <- obj.csc
  if (map == "contribution") obj.crd <- obj.ccc
  if (!map %in% c("symmetric", "asymmetric", "contribution")) {
    stop("map option is not a valid choice of present options: symmetric, asymmetric, contribution")
  }

  # 3b. INCLUDE ONLY MOST CONTRIBUTING IF most=TRUE
  col_include <- rep(TRUE, nrow(obj.ccc))
  if (most) {
    for (j in 1:nrow(obj.ccc)) {
      col_include[j] <- (obj.ccc[j, dim[1]]^2 > 1/nrow(obj.ccc)) || (obj.ccc[j, dim[2]]^2 > 1/nrow(obj.ccc))
    }
  }

  # 4. COMPUTE INERTIA VARIANCE PERCENTAGES SLICES NATIVELY
  tot_sv2  <- sum(obj$sv^2)
  perc.hor <- 100 * obj$sv[dim[1]]^2 / tot_sv2
  perc.ver <- 100 * obj$sv[dim[2]]^2 / tot_sv2

  # 5. NAME FALLBACK INTEGRITY CHECKS
  if (labelrows && is.null(obj$rownames)) {
    warning("Object does not contain '$rownames'. Falling back to numeric row indices.")
    plot_rownames <- 1:nrow(obj.rpc)
  } else {
    plot_rownames <- if (!is.null(obj$rownames)) obj$rownames else 1:nrow(obj.rpc)
  }
  plot_colnames <- if (!is.null(obj$colnames)) obj$colnames else 1:nrow(obj.crd)

  # 6. INITIALIZE R GRAPHICS CANVAS
  if (rescale == 1) {
    plot(1.05 * rbind(obj.rpc, rescale * obj.crd), type = "n", asp = 1, 
         xlab = paste(classobj, " dimension ", dim[1], " (", round(perc.hor, 1), "%)", sep = ""), 
         ylab = paste(classobj, " dimension ", dim[2], " (", round(perc.ver, 1), "%)", sep = ""),
         main = main, cex.axis = 0.8)
  } else {
    plot(1.05 * rbind(obj.rpc, rescale * obj.crd), type = "n", asp = 1, 
         xlab = paste(classobj, " dimension ", dim[1], " (", round(perc.hor, 1), "%)", sep = ""), 
         ylab = paste(classobj, " dimension ", dim[2], " (", round(perc.ver, 1), "%)", sep = ""),
         xaxt = "n", yaxt = "n", main = main, cex.axis = 0.8)
    
    axis(1, col.ticks = cols[1], col.axis = cols[1])
    axis(2, col.ticks = cols[1], col.axis = cols[1])
    axis(3, at = axTicks(3), labels = round(axTicks(3) / rescale, 2),  col.ticks = cols[2], col.axis = cols[2])
    axis(4, at = axTicks(4), labels = round(axTicks(4) / rescale, 2),  col.ticks = cols[2], col.axis = cols[2])
  }
  
  abline(h = 0, v = 0, col = "gray", lty = 2)

  # 9. COMPOSITIONAL ELLIPSES ACCENT GENERATOR
  if (!is.na(ellipse)) {
    if (!requireNamespace("ellipse", quietly = TRUE)) {
      stop("The 'ellipse' package must be installed and loaded to display confidence ellipses.")
    }
    
    # FIXED: Adaptive internal slicing logic for tracking supplementary subsets
    has_suprow <- !is.null(obj$rowsup) && !all(is.na(obj$rowsup))
    
    if (ellipse.sup && has_suprow) {
      ellipse_coords <- obj.rpc[obj$rowsup, , drop = FALSE]
      
      # Automatically slice group factor length to match passive sample count securely
      if (length(group) == nrow(obj.rpc)) {
        ellipse_group <- group[obj$rowsup]
      } else {
        ellipse_group <- group
      }
    } else {
      ellipse_coords <- obj.rpc
      ellipse_group  <- group
    }
    
    set.seed(123)
    CIplot_biv(ellipse_coords[, 1], ellipse_coords[, 2], group = ellipse_group, groupcols = groupcols, shownames = FALSE,
               add = TRUE, shade = TRUE, alpha = conf, cex = 0.8, ellipse = ellipse)
    set.seed(123)
    # Check bounds safety before passing names
    display_groupnames <- if(!all(is.na(groupnames))) groupnames else NULL
    CIplot_biv(ellipse_coords[, 1], ellipse_coords[, 2], group = ellipse_group, groupcols = groupcols, 
               add = TRUE, cex = 0.8, alpha = conf, groupnames = display_groupnames, ellipse = ellipse)
  }
  
  # 7. RENDER COLUMN BI-PLOT OVERLAY ARROWS
  if (map != "symmetric" && arrows) {
    arrows(0, 0, 0.95 * rescale * obj.crd[col_include, 1], 0.95 * rescale * obj.crd[col_include, 2], 
           length = 0.1, angle = 10, col = colarrows, lwd = 2)
  }
  
  # 8. RESTRUCTURED GRAPHICS TEXT & DATA POINTS ENGINE
  if (labelrows) {
    if (all(is.na(groupcols))) {
      text(obj.rpc, labels = plot_rownames, col = cols[1], font = fonts[1], cex = cexs[1])
    } else {
      # Handle color plotting indexing if group factor length matches only passive rows
      if (length(group) == nrow(obj.rpc)) {
        text(obj.rpc, labels = plot_rownames, col = groupcols[group], font = fonts[1], cex = cexs[1])
      } else {
        # Fallback for short vectors: color active centroids uniformly, then color passive sample groups
        n_centroids <- nrow(obj.rpc) - length(group)
        full_color_idx <- c(rep(cols[1], n_centroids), groupcols[group])
        text(obj.rpc, labels = plot_rownames, col = full_color_idx, font = fonts[1], cex = cexs[1])
      }
    }
  } else {
    if (all(is.na(groupcols)) && all(is.na(grouppchs))) {
      points(obj.rpc, pch = 1, col = cols[1], cex = cexs[1])
    } else if (!all(is.na(groupcols)) && all(is.na(grouppchs))) {
      points(obj.rpc, pch = 1, col = groupcols[group], cex = cexs[1])
    } else if (all(is.na(groupcols)) && !all(is.na(grouppchs))) {
      points(obj.rpc, pch = grouppchs, col = cols[1], cex = cexs[1])
    } else if (!all(is.na(groupcols)) && !all(is.na(grouppchs))) {
      points(obj.rpc, pch = grouppchs[group], col = groupcols[group], cex = cexs[1])
    }
  }
  
  # Render final text layouts for components labels 
  text(rescale * obj.crd[col_include, , drop = FALSE], labels = plot_colnames[col_include], col = cols[2], font = fonts[2], cex = cexs[2])
  
  # Render final map tracking labels block legend
  if (!all(is.na(legendpos))) {
    legend_pch <- if (labelrows) NULL else (if (all(is.na(grouppchs))) 1 else grouppchs)
    legend(legendpos, legend = groupnames, pch = legend_pch, col = groupcols, text.col = groupcols, cex = 0.8)
  }
}

Try the easyCODA package in your browser

Any scripts or data that you put into this service are public.

easyCODA documentation built on Nov. 24, 2026, 1:07 a.m.