R/plot-style.R

Defines functions pm_sig_bars pm_group_scales pm_plot_args pm_curve_style pm_base_par pm_plot_via_autoplot pm_bar_clip pm_clip_interval pm_point_alpha pm_theme

## Colours, transparency and sizes of every predictmeans plot, in one place
## (dev/review-plot-style.md). No colour is set outside this file.
## A band is drawn first, its line on top in a darker shade of the same hue
## (a band drawn over its line hides it); the reference line (0, or 1 for
## ratios) is dashed red, as in 1.x, and the stretches where the band leaves
## out the reference are marked under the curve. Groups take a palette that
## colour-blind readers can tell apart (Okabe and Ito).
pm_style_defaults <- list(
  line = "#08519C", band = "#6BAED6",             # one curve or estimate: dark and light blue
  diff_line = "#00441B", diff_band = "#74C476",   # a difference of two curves: dark and light green
  ref = "#CB181D",                                # the reference line and the marks: red
  alpha = 0.30, linewidth = 1,
  points = "grey30", point_alpha = 0.6, point_size = 1.3,
  # Okabe-Ito, black moved up: the first five have 3:1 contrast on white, the last three (orange, sky blue,
  # yellow) do not and come only with six or more groups
  palette = c("#0072B2", "#D55E00", "#009E73", "#CC79A7", "#000000", "#E69F00", "#56B4E9", "#F0E442"),
  surface_points = "#CB181D",
  ref_linewidth = 0.8, ref_linetype = 2,          # thicker than ggplot's 0.5 (maintainer, 2026-12-02)
  guide = "grey40",                               # residual, QQ and 1:1 guide lines (not tests)
  trend = "#D55E00",                              # smooths through residuals (orange: apart from the red reference)
  bar_fill = "#9ECAE1",                           # bars of means
  lsd = "grey20",                                 # the LSD/SED bar: a ruler, not a line of no difference
  seq_low = "#F7FBFF", seq_high = "#08306B",      # sequential fills (bins, surfaces)
  p_bands4 = c("#0D0DFF", "#5D5DFF", "#A1A1FF", "#E4E4FF"), p_bands2 = c("#0D0DFF", "#C9C9FF")  # p-value tiles
)

## The names 'plot_args' of semipred()/covariatemeans() and 'style' of
## autoplot.pm_curves() accept (those of 1.x and 2.0 curve plots).
pm_curve_style_defaults <- pm_style_defaults[c("line", "band", "diff_line", "diff_band", "ref", "alpha", "linewidth",
                                               "points", "point_alpha", "point_size", "palette", "surface_points")]

## The theme of every ggplot: theme_bw() with a light major grid, no minor
## grid and the legend on top; 'open' for bar charts (axis lines, no grid,
## no box).
pm_theme <- function(base_size = 11, open = FALSE) {
  th <- ggplot2::theme_bw(base_size = base_size) +
    ggplot2::theme(panel.grid.minor = ggplot2::element_blank(),
                   panel.grid.major = ggplot2::element_line(colour = "grey92", linewidth = 0.3),
                   strip.background = ggplot2::element_rect(fill = "grey95", colour = "grey70"),
                   legend.position = "top")
  if (open) th <- th + ggplot2::theme(panel.border = ggplot2::element_blank(), panel.grid.major = ggplot2::element_blank(),
                                      axis.line = ggplot2::element_line(colour = "grey20"))
  th
}

## Transparency of 'n' points: the style's, lowered for many points so dense
## regions show (n > 200: 20 / sqrt(n), at least 0.15).
pm_point_alpha <- function(n, style = pm_style_defaults) {
  if (n > 200) max(0.15, 20 / sqrt(n)) else style$point_alpha
}

## Intervals of bars cut at the bar's baseline 0: a bar of a positive mean
## shows [max(lo, 0), hi], of a negative mean [lo, min(hi, 0)]. For plots
## only; the tables keep the full limits. Returns lo, hi and which ends were
## cut (those are drawn without a cap).
pm_clip_interval <- function(y, lo, hi) {
  if (length(lo) != length(y) || length(hi) != length(y)) stop("y, lo and hi must have the same length.", call. = FALSE)
  pos <- !is.na(y) & y >= 0
  neg <- !is.na(y) & y < 0
  cut_lo <- pos & !is.na(lo) & lo < 0
  cut_hi <- neg & !is.na(hi) & hi > 0
  lo[cut_lo] <- 0
  hi[cut_hi] <- 0
  list(lo = lo, hi = hi, cut_lo = cut_lo, cut_hi = cut_hi)
}

## The intervals of a bar chart cut at 0 panel by panel (maintainer's choice
## (a), dev/review-plot-style.md): only in panels where all bars have the same
## sign; across signs a cut could hide an overlap of comparison intervals.
## 'key': the panel of each row. Returns the means with lo, hi, cap_lo, cap_hi
## (NA at a cut end: drawn without a cap) and attr "status": "cut" when an
## interval was cut, "mixed" when a panel crossing 0 was left whole, else "".
pm_bar_clip <- function(means, key) {
  same <- tapply(means$y, key, function(v) all(v >= 0, na.rm = TRUE) || all(v < 0, na.rm = TRUE))[key]
  cl <- pm_clip_interval(means$y, means$lo, means$hi)
  ok <- same & !is.na(same)
  would <- cl$cut_lo | cl$cut_hi
  means$lo <- ifelse(ok, cl$lo, means$lo)
  means$hi <- ifelse(ok, cl$hi, means$hi)
  means$cap_lo <- ifelse(ok & cl$cut_lo, NA_real_, means$lo)
  means$cap_hi <- ifelse(ok & cl$cut_hi, NA_real_, means$hi)
  attr(means, "status") <- c(if (any(ok & would)) "cut", if (any(!ok & would)) "mixed")
  means
}

## plot() of every class with an autoplot() method: draw the ggplot and
## return it invisibly (one place; dev/review-plot-style.md, decision 7).
## The object is '.object': autoplot.predictmeans() has an argument 'x'.
pm_plot_via_autoplot <- function(.object, ...) {
  p <- ggplot2::autoplot(.object, ...)
  print(p)
  invisible(p)
}

## The same colours and widths for base-graphics plots (permlmer(plot = TRUE)).
## ggplot draws linewidth in mm, base lwd in units of 1/96 inch: lwd = linewidth * .pt.
pm_base_par <- function(style = pm_style_defaults) {
  list(col = style$line, lwd = style$linewidth * ggplot2::.pt, ref = style$ref,
       ref_lwd = style$ref_linewidth * ggplot2::.pt, ref_lty = style$ref_linetype)
}

## The plot settings of semipred() ('plot_args', with the colours above).
pm_semi_plot_defaults <- list(trellis = TRUE, scales = "fixed", plotord = NULL, ci = TRUE, point = TRUE, jitterv = 0,
                              threeD = FALSE)

pm_curve_style <- function(plot_args = list()) {
  if (!is.list(plot_args) || (length(plot_args) && (is.null(names(plot_args)) || !all(nzchar(names(plot_args)))))) {
    stop("'plot_args' must be a named list, e.g. plot_args = list(line = \"black\", band = \"grey70\").", call. = FALSE)
  }
  bad <- setdiff(names(plot_args), names(pm_curve_style_defaults))
  if (length(bad)) {
    stop("'plot_args' can hold ", paste(names(pm_curve_style_defaults), collapse = ", "), "; not ",
         paste(bad, collapse = ", "), ".", call. = FALSE)
  }
  utils::modifyList(pm_curve_style_defaults, plot_args)
}

## The plot settings of a call ('plot_args' of covariatemeans() and
## semipred(); names may be abbreviated), with the 'defaults' of the calling
## function for those not given.
pm_plot_args <- function(plot_args = list(), defaults) {
  nms <- names(defaults)
  if (!is.list(plot_args) || (length(plot_args) && (is.null(names(plot_args)) || !all(nzchar(names(plot_args)))))) {
    stop("'plot_args' must be a named list, e.g. plot_args = list(mtitle = \"Yield\").", call. = FALSE)
  }
  k <- pmatch(names(plot_args), nms, duplicates.ok = TRUE)
  if (anyNA(k)) stop("'plot_args' can hold ", paste(nms, collapse = ", "), "; not ",
                     paste(names(plot_args)[is.na(k)], collapse = ", "), call. = FALSE)
  out <- defaults
  for (i in seq_along(k)) out[nms[k[i]]] <- list(plot_args[[i]])
  out
}

## Colour and fill scales for curves by group: the palette when it has enough
## colours, else ggplot2's own.
pm_group_scales <- function(style, n, name = ggplot2::waiver()) {
  # the style's palette while it has enough colours, else evenly spaced hues;
  # the same values and name for colour and fill, so the line and band keys
  # merge into one legend
  pal <- if (n <= length(style$palette)) style$palette[seq_len(n)] else grDevices::hcl.colors(n, "Dark 3")
  list(ggplot2::scale_colour_manual(values = pal, name = name, drop = FALSE),
       ggplot2::scale_fill_manual(values = pal, name = name, drop = FALSE))
}

## Bars along the bottom of the panel for the stretches of x where a band
## leaves out the reference ('sig': data frame with from, to); each widened by
## half a grid step so a single point shows too. Drawn as a rug, which sits at
## the panel edge without a y value: y = -Inf became NaN on the log axis of
## ratio and odds-ratio plots, and the bars were dropped.
pm_sig_bars <- function(sig, x, style) {
  if (is.null(sig) || !nrow(sig)) return(NULL)
  ux <- sort(unique(x))
  step <- if (length(ux) > 1) stats::median(diff(ux)) / 2 else 0
  # the points of x in each stretch, widened by half a step, as a dense rug
  pts <- unlist(lapply(seq_len(nrow(sig)), function(i) {
    seq(sig$from[i] - step, sig$to[i] + step, length.out = max(2, 200 * (sig$to[i] - sig$from[i] + 2 * step) /
                                                                  max(diff(range(ux)), .Machine$double.eps)))
  }))
  ggplot2::geom_rug(data = data.frame(x = pts), ggplot2::aes(x = .data$x), sides = "b", colour = style$ref,
                    linewidth = 1.2, length = ggplot2::unit(0.02, "npc"), inherit.aes = FALSE)
}

Try the predictmeans package in your browser

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

predictmeans documentation built on Dec. 3, 2026, 5:07 p.m.