R/plt.mat.R

Defines functions .plt.mat

.plt.mat <-
function(x, cor.coef=TRUE, fit="loess",
         col_fill=getOption("pt_fill"), col_color=getOption("pt_color"),
         col.fit=getOption("fit_color"), col.bg=getOption("panel_fill"),
         col.box=getOption("panel_color"),
         col_trans=getOption("trans_pt_fill"),
         pt.size=pt.size, size.miss=size.miss,
         render="scatter", theme=getOption("theme"),
         contour_n=8, contour_nbins=50, contour_points=FALSE,
         smooth_bins=128, smooth_power=0.25) {

  # each cell is a different pair of variables, in its own units, so unlike
  #   the faceted contour there is no common bandwidth or density scale to
  #   pool: every cell gets its own kernel density and its own bands
  dens <- render %in% c("contour", "smooth")
  smooth <- identical(render, "smooth")

  if (dens) {
    if (smooth) {
      hue <- .get.h(theme)
      satur <- ifelse(theme %in% c("gray", "white"), 0, 80)
      col.s <- colorRampPalette(c(getOption("window_fill"),
                                  hcl(hue, satur, 16)))(256)
    }
    else {
      if (theme %in% c("white", "gray", "light")) {
        clrs <- colorRampPalette(c("white",
          gray.colors(contour_n, rev=TRUE, start=0.20, end=0.92)))
      }
      else {
        sc <- .corcolors()
        clrs <- colorRampPalette(c("white", getColors(sc$fill_hi)))
      }
      col.n <- clrs(contour_n)
    }
    n.grid <- if (smooth) smooth_bins else contour_nbins
  }


  panel.dens <- function(x, y, ...) {

    my.usr <- par("usr")
    rect(my.usr[1], my.usr[3], my.usr[2], my.usr[4],
         col=col.bg, border=col.box)

    ok <- is.finite(x) & is.finite(y)
    if (sum(ok) < 3) return(invisible(NULL))
    xo <- x[ok]; yo <- y[ok]

    h <- c(MASS::bandwidth.nrd(xo), MASS::bandwidth.nrd(yo))
    if (any(h <= 0)) return(invisible(NULL))  # collinear or constant

    d <- MASS::kde2d(xo, yo, n=n.grid, h=h,
                     lims=c(my.usr[1:2], my.usr[3:4]))

    if (smooth)
      image(d$x, d$y, d$z ^ smooth_power, col=col.s,
            add=TRUE, useRaster=TRUE)
    else {
      lv.z <- seq(min(d$z), max(d$z), length.out=contour_n + 1)
      .filled.contour(d$x, d$y, d$z, levels=lv.z, col=col.n)
      if (contour_points)
        points(xo, yo, pch=21, cex=0.5, bg="#00000044",
               col="white", lwd=0.2)
    }

    # the density is the summary, so a fitted curve is drawn without its
    #   confidence band, which would obscure the bands beneath it
    if (fit %in% c("loess", "lm")) {
      if (fit == "loess")
        lines(lowess(xo, yo), col=col.fit)
      else {
        l.ln <- lm(yo ~ xo)
        oo <- order(xo)
        lines(xo[oo], fitted(l.ln)[oo], col=col.fit)
      }
    }

    box(col=col.box)
  }


  panel.smooth <- function(x, y, fit.line=fit, pch=par("pch"), cex=.76,
    col.pt=col_color, col.smooth=col.fit, span=2/3, iter=3, ...) {

    my.usr <- par("usr")          
    rect(my.usr[1], my.usr[3], my.usr[2], my.usr[4], col=col.bg, border=col.box)
    cex.adj <- ifelse(size.miss, 0.80 - 0.048*n.var, pt.size)
    points(x, y, pch=21, col=col.pt, bg=col_fill, cex=cex.adj)

    ok <- is.finite(x) & is.finite(y)
    if (any(ok)) {
      if (fit.line %in% c("loess", "lm")) {
        yo <- order(x[ok])  # need to order x, then have y follow
        x[ok] <- sort(x[ok])
        y[ok] <- y[ok][yo]
        if (fit.line == "loess") {
          l.ln <- loess(y[ok] ~ x[ok])
          lines(lowess(x[ok], y[ok], f=span, iter=iter), col=col.smooth, ...)
        }
        else if (fit.line == "lm") {
          l.ln <- lm(y[ok] ~ x[ok])
          lines(x[ok], fitted(l.ln), col=col.smooth, ...)
        }
        f.ln <- fitted(l.ln, ...)
        p.ln <- predict(l.ln, se=TRUE) # get standard errors
        if (is.finite(p.ln$df) && p.ln$df > 0) {  # residual df of the fit
          prb <- (1 - 0.95) / 2 # 0.95 confidence level
          up.ln <- f.ln + (qt(prb, p.ln$df) * p.ln$se.fit)
          dn.ln <- f.ln - (qt(prb, p.ln$df) * p.ln$se.fit)
          polygon(c(x[ok], rev(x[ok])), c(dn.ln, rev(up.ln)),
            col=getOption("se_fill"), border="transparent") #
        }
      }
    }
  }


  panel.cor <- function(x, y, ...) {
    my.usr <- par("usr"); on.exit(par(usr = my.usr))
    rect(my.usr[1], my.usr[3], my.usr[2], my.usr[4], col=col.bg, border=col.box)
    par(usr=c(0, 1, 0, 1))
    r <- cor(x, y)
    txt <- .fmt(r, 2)
    # maybe use par("fin")[1] / n.var to get size of each cell
    cex.adj <- 1.6 - (0.065*n.var)  # adjust size of displayed r   # 1.274
    text(0.5, 0.5, txt, cex=cex.adj, col="black")  # or cex=cex.cor * r
  }


  text.diag <- function(x, y, nm, ...) {  # nm from calling routine
    my.usr <- par("usr")          
    rect(my.usr[1], my.usr[3], my.usr[2], my.usr[4], col=getOption("se_fill"),
         border=col.box)
    cex.adj <- 1.6 - (0.065*n.var)  # adjust size of displayed var name
    text(0.5, 0.5, nm, cex=cex.adj, col=getOption("lab_color"))
  }

  # -----
  # begin

  if (is.logical(fit)) if (fit) fit <- "loess"

  if (getOption("sub_theme") == "black")
     col_color <- getOption("lab_color")

  n.var <- ncol(x)

  par(bg=getOption("window_fill"))

  if (!is.null(col_trans))
    col_fill <- .maketrans(col_fill, (1-col_trans)*256)

  lower.fn <- if (dens) panel.dens else panel.smooth

  if (cor.coef)  # no missing data
    pairs(na.omit(x), lower.panel=lower.fn, upper.panel=panel.cor,
      text.panel=text.diag)
  else
    pairs(na.omit(x), panel=lower.fn, text.panel=text.diag)

}

Try the lessR package in your browser

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

lessR documentation built on Nov. 4, 2026, 1:07 a.m.