R/plot_pred.R

Defines functions .as_pred .emptiest_corner .pred_xy plot.wnpmle_pred

Documented in plot.wnpmle_pred

#' Plot predicted cumulative incidences or marginal means
#'
#' Plots the result of \code{predict()} for a \code{wnpmle} fit: one curve per
#' row of \code{newdata}, with pointwise confidence bands. For competing-risks
#' fits (\code{type = "cmprsk"}) the curves are cumulative incidences, for
#' recurrent events marginal means.
#'
#' @param x Result of \code{predict()} for a \code{wnpmle} fit.
#' @param conf_int Logical; draw the pointwise confidence bands, if available
#'   (default \code{TRUE}, \code{FALSE} with \code{add = TRUE}).
#' @param add Logical; add the curves to the current plot, e.g. to compare two
#'   models (default \code{FALSE}). Added curves are dashed by default.
#' @param xscale The time axis is divided by \code{xscale}, e.g.
#'   \code{xscale = 365.25} to show days in years (default 1).
#' @param type \code{"s"} (step function, default) or \code{"l"} (lines).
#' @param col,lty,lwd Colour, line type and line width, recycled over the
#'   curves. Default: grey shades from black, solid lines (dashed with
#'   \code{add = TRUE}).
#' @param band_col Colour of the confidence bands (default: \code{col}).
#' @param band_alpha Transparency of the confidence bands (default 0.15).
#' @param labels Legend labels, one per curve. By default built from the
#'   covariates that differ between the rows of \code{newdata}.
#' @param legend Position of the legend, e.g. \code{"topleft"};
#'   \code{"auto"} (default) puts it in the emptiest corner, \code{FALSE}
#'   draws no legend (default with \code{add = TRUE}).
#' @param xlab,ylab,main,xlim,ylim Axis labels, title and axis limits. The
#'   y-axis label depends on the type of prediction.
#' @param ... Further graphical parameters passed to \code{plot()} (not used
#'   with \code{add = TRUE}).
#' @return \code{x}, invisibly.
#' @examples
#' \donttest{
#' library(survival)
#' tp <- survival::transplant
#' tp <- tp[tp$futime > 0 & complete.cases(tp), ]
#' tp$status <- ifelse(tp$event == "ltx", 1, ifelse(tp$event == "censored", 0, 2))
#' fit <- wnpmle_fit(Surv(futime, status) ~ age + sex + abo, data = tp,
#'                   type = "cmprsk", model = "boxcox", rho = 1)
#' nd <- data.frame(age = 50, sex = factor("m", levels = levels(tp$sex)),
#'                  abo = factor(c("A", "O"), levels = levels(tp$abo)))
#' p <- predict(fit, newdata = nd)
#' plot(p, xscale = 365.25, xlab = "Years on the waiting list")
#' }
#' @export
plot.wnpmle_pred <- function(x, conf_int = !add, add = FALSE, xscale = 1,
                             type = c("s", "l"), col = NULL, lty = NULL,
                             lwd = NULL, band_col = NULL, band_alpha = 0.15,
                             labels = NULL, legend = if (add) FALSE else "auto",
                             xlab = NULL, ylab = NULL, main = NULL,
                             xlim = NULL, ylim = NULL, ...) {
  type <- match.arg(type)
  what <- attr(x, "what")
  if (is.null(what)) what <- "mu"
  nm  <- names(x)
  est <- grep(paste0("^", what, "(_[0-9]+)?$"), nm, value = TRUE)
  if (!length(est)) stop("no predictions found in 'x'")
  suf <- sub(paste0("^", what), "", est)
  k   <- length(est)
  tt  <- x$time / xscale
  has_ci <- isTRUE(conf_int) && all(c(paste0("lower", suf), paste0("upper", suf)) %in% nm)

  if (is.null(col)) col <- if (k == 1) "black" else grDevices::gray(seq(0, 0.55, length.out = k))
  if (is.null(lty)) lty <- if (add) 2 else 1
  if (is.null(lwd)) lwd <- if (add) 1.5 else 2
  col <- rep_len(col, k); lty <- rep_len(lty, k); lwd <- rep_len(lwd, k)
  band_col <- rep_len(if (is.null(band_col)) col else band_col, k)

  if (!add) {
    if (is.null(xlab)) xlab <- "Time"
    if (is.null(ylab)) ylab <- if (what == "cif") "Cumulative incidence" else "Marginal mean"
    if (is.null(main)) main <- ""
    if (is.null(xlim)) xlim <- range(tt, finite = TRUE)
    if (is.null(ylim)) {
      ymax <- max(unlist(x[c(est, if (has_ci) paste0("upper", suf))]), na.rm = TRUE)
      if (what == "cif") ymax <- min(ymax, 1)
      ylim <- c(0, 1.04 * ymax)
    }
    graphics::plot(NA, xlim = xlim, ylim = ylim, xlab = xlab, ylab = ylab,
                   main = main, ...)
  }

  if (has_ci) {
    for (i in seq_len(k)) {
      lo <- .pred_xy(tt, x[[paste0("lower", suf[i])]], type)
      up <- .pred_xy(tt, x[[paste0("upper", suf[i])]], type)
      ok <- is.finite(lo$y) & is.finite(up$y)
      graphics::polygon(c(lo$x[ok], rev(up$x[ok])), c(lo$y[ok], rev(up$y[ok])),
                        col = grDevices::adjustcolor(band_col[i], band_alpha),
                        border = NA)
    }
  }
  for (i in seq_len(k)) {
    xy <- .pred_xy(tt, x[[est[i]]], type)
    graphics::lines(xy$x, xy$y, col = col[i], lty = lty[i], lwd = lwd[i])
  }

  if (is.null(labels) && k > 1) {
    nd <- attr(x, "newdata")
    if (!is.null(nd) && nrow(nd) == k) {
      vary <- names(nd)[vapply(nd, function(v) length(unique(as.character(v))) > 1,
                               logical(1))]
      if (length(vary))
        labels <- vapply(seq_len(k), function(i)
          paste(paste(vary, "=", vapply(nd[i, vary, drop = FALSE], as.character,
                                        character(1))), collapse = ", "),
          character(1))
    }
    if (is.null(labels)) labels <- paste("Row", seq_len(k))
  }
  if (!isFALSE(legend) && !is.null(labels)) {
    pos <- if (identical(legend, "auto")) {
      ys <- c(est, if (has_ci) c(paste0("lower", suf), paste0("upper", suf)))
      .emptiest_corner(tt, x[ys])
    } else legend
    graphics::legend(pos, legend = labels, col = col, lty = lty, lwd = lwd,
                     bty = "n", cex = 0.8, seg.len = 3, inset = 0.02)
  }
  invisible(x)
}

# coordinates of a step function ("s") or of a line ("l")
.pred_xy <- function(t, y, type) {
  n <- length(t)
  if (type == "l" || n < 2) return(list(x = t, y = y))
  list(x = c(t[1], rep(t[-1], each = 2)), y = c(rep(y[-n], each = 2), y[n]))
}

# corner of the current plot region with the fewest curve points
.emptiest_corner <- function(t, ylist) {
  u  <- graphics::par("usr")
  gx <- seq(u[1], u[2], length.out = 200)
  fy <- unlist(lapply(ylist, function(y) {
    ok <- is.finite(t) & is.finite(y)
    if (sum(ok) < 2) return(numeric(0))
    stats::approx(t[ok], y[ok], xout = gx, method = "constant", rule = 2, f = 0, ties = max)$y
  }))
  fx <- rep((gx - u[1]) / (u[2] - u[1]), length.out = length(fy))
  fy <- (fy - u[3]) / (u[4] - u[3])
  w <- 0.45; h <- 0.35
  cnt <- c(topleft     = sum(fx < w & fy > 1 - h),
           topright    = sum(fx > 1 - w & fy > 1 - h),
           bottomright = sum(fx > 1 - w & fy < h),
           bottomleft  = sum(fx < w & fy < h))
  names(cnt)[which.min(cnt)]
}

# predict() results get class "wnpmle_pred" (still a data frame)
.as_pred <- function(out, what, newdata) {
  attr(out, "what")    <- what
  attr(out, "newdata") <- newdata
  class(out) <- c("wnpmle_pred", class(out))
  out
}

Try the wnpmle package in your browser

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

wnpmle documentation built on Dec. 1, 2026, 9:06 a.m.