R/plots.R

Defines functions plotResidualsPanels plotResidualsAll plotConventionalResiduals plotResiduals plotQQunif plotSimulatedResiduals hist.DHARMa plot.DHARMa

Documented in hist.DHARMa plotConventionalResiduals plot.DHARMa plotQQunif plotResiduals plotResidualsAll plotSimulatedResiduals

#' DHARMa standard residual plots
#'
#' This S3 function creates standard plots for the simulated residuals contained in an object of class DHARMa, using [plotQQunif] (left panel) and [plotResiduals] (right panel).
#'
#' @param x an object of class DHARMa with simulated residuals created by [simulateResiduals].
#' @param ... further options for [plotResiduals]. Consider in particular parameters quantreg, rank and asFactor. xlab, ylab and main passed here only change the right panel (the residual plot); use [plotResiduals] and [plotQQunif] to fully control the labels of the individual plots.
#' @param title the title for both panels (plotted via mtext, outer = TRUE).
#'
#' @details The function creates a plot with two panels. The left panel is a uniform qq plot (calling [plotQQunif]), and the right panel shows residuals against predicted values (calling [plotResiduals]), with outliers as a star/asterisk and highlighted in red if outlier test is significant (default color but see Note).
#'
#' Very briefly, we would expect that a correctly specified model shows:
#'
#' a) a straight 1-1 line, as well as non-significance of the displayed tests in the qq-plot (left) -> evidence for a correct overall residual distribution (for more details on the interpretation of this plot, see [plotQQunif])
#'
#' b) visual homogeneity of residuals in both vertical and horizontal direction, as well as non-significance of quantile tests in the res ~ predictor plot (for more details on the interpretation of this plot, see [plotResiduals])
#'
#' Deviations from these expectations can be interpreted similar to a linear regression. See the vignette for detailed examples.
#'
#' @note The color for highlighting outliers and significant tests can be changed by setting \code{options(DHARMaSignalColor = "red")} to a different color. See \code{getOption("DHARMaSignalColor")} for the current setting. This is convenient for a color-blind friendly display, since red and black are difficult for some people to separate.
#'
#' @seealso [plotResiduals], [plotQQunif]
#' @example inst/examples/plotsHelp.R
#' @import graphics
#' @import utils
#' @export
plot.DHARMa <- function(x, title = "DHARMa residual", ...){

  oldpar <- par(mfrow = c(1,2), oma = c(0,1,2,1))
  on.exit(par(oldpar))

  plotQQunif(x)
  plotResiduals(x, ...)

  mtext(title, outer = TRUE)
}


#' Histogram of DHARMa residuals
#'
#' The function produces a histogram from a DHARMa output. Outliers are marked in red.
#'
#' @param x a DHARMa simulation output (class DHARMa).
#' @param breaks breaks for hist() function.
#' @param col color for histogram bars.
#' @param main plot title.
#' @param xlab plot x-axis label.
#' @param cex.main plot cex.main.
#' @param ... other arguments to be passed on to hist().
#' @details The function calls hist() to create a histogram of the scaled residuals. Outliers are marked red as default but it can be changed by setting \code{options(DHARMaSignalColor = "red")} to a different color. See \code{getOption("DHARMaSignalColor")} for the current setting.
#' @seealso [plot.DHARMa], [plotResiduals]
#' @example inst/examples/plotsHelp.R
#' @export
hist.DHARMa <- function(x,
                        breaks = seq(-0.02, 1.02, len = 53),
                        col = c(.Options$DHARMaSignalColor,rep("lightgrey",50), .Options$DHARMaSignalColor),
                        main = "Hist of DHARMa residuals",
                        xlab = "Residuals (outliers are marked red)",
                        cex.main = 1,
                        ...){

  x = ensureDHARMa(x, convert = TRUE)

  val = x$scaledResiduals
  val[val == 0] = -0.01
  val[val == 1] = 1.01

  hist(val, breaks = breaks, col = col, main = main, xlab = xlab, cex.main = cex.main, ...)
}


#' DHARMa standard residual plots (deprecated)
#'
#' DEPRECATED, use plot() instead
#'
#' @param simulationOutput an object with simulated residuals created by [simulateResiduals]
#' @param ... further options for [plotResiduals]. Consider in particular parameters quantreg, rank and asFactor. xlab, ylab and main passed here only change the right panel (the residual plot); use [plotResiduals] and [plotQQunif] to fully control the labels of the individual plots.
#' @note This function is deprecated. Use [plot.DHARMa]
#'
#' @seealso [plotResiduals], [plotQQunif]
#' @export
plotSimulatedResiduals <- function(simulationOutput, ...){
  message("plotSimulatedResiduals is deprecated, please switch your code to simply using the plot() function")
  plot(simulationOutput, ...)
}


#' Quantile-quantile plot for a uniform distribution
#'
#' The function produces a uniform quantile-quantile plot from a DHARMa output. Optionally, tests for uniformity, outliers and dispersion can be added.
#'
#' @param simulationOutput a DHARMa simulation output (class DHARMa).
#' @param testUniformity if T, the function [testUniformity] will be called and the result will be added to the plot.
#' @param testOutliers if T, the function [testOutliers] will be called and the result will be added to the plot.
#' @param testDispersion if T, the function [testDispersion] will be called and the result will be added to the plot.
#' @param ... arguments to be passed on to [gap::qqunif].
#'
#' @details The function calls qqunif() from the R package gap to create a quantile-quantile plot for a uniform distribution, and overlays tests for particular distributional problems as specified.
#' When tests are displayed, significant p-values are highlighted in the color red by default. This can be changed by setting \code{options(DHARMaSignalColor = "red")} to a different color. See \code{getOption("DHARMaSignalColor")} for the current setting.
#' @seealso [plot.DHARMa], [plotResiduals]
#' @example inst/examples/plotsHelp.R
#' @export
plotQQunif <- function(simulationOutput, testUniformity = TRUE, testOutliers = TRUE, testDispersion = TRUE, ...){

  a <- list(...)
  a$pch = checkDots("pch", 2, ...)
  a$bty = checkDots("bty", "n", ...)
  a$logscale = checkDots("logscale", F, ...)
  a$col = checkDots("col", "black", ...)
  a$main = checkDots("main", "QQ plot residuals", ...)
  a$cex.main = checkDots("cex.main", 1, ...)
  a$xlim = checkDots("xlim", c(0,1), ...)
  a$ylim = checkDots("ylim", c(0,1), ...)

  simulationOutput = ensureDHARMa(simulationOutput, convert = "Model")

  do.call(gap::qqunif, append(list(simulationOutput$scaledResiduals), a))

  if(testUniformity == TRUE){
    temp = testUniformity(simulationOutput, plot = FALSE)
    legend("topleft",
           c(paste("KS test: p=", round(temp$p.value, digits = 5)),
             paste("Deviation ", ifelse(temp$p.value < 0.05, "significant", "n.s."))),
           text.col = ifelse(temp$p.value < 0.05, .Options$DHARMaSignalColor, "black" ), bty="n")

  }

  if(testOutliers == TRUE){
    temp = testOutliers(simulationOutput, plot = FALSE)
    legend("bottomright",
           c(paste("Outlier test: p=", round(temp$p.value, digits = 5)),
             paste("Deviation ", ifelse(temp$p.value < 0.05, "significant", "n.s."))),
           text.col = ifelse(temp$p.value < 0.05, .Options$DHARMaSignalColor, "black" ), bty="n")

  }

  if(testDispersion == TRUE){
    temp = testDispersion(simulationOutput, plot = FALSE)
    legend("center",
           c(paste("Dispersion test: p=", round(temp$p.value, digits = 5)),
             paste("Deviation ", if(is.na(temp$p.value)) "not available" else ifelse(temp$p.value < 0.05, "significant", "n.s."))),
           text.col = ifelse(isTRUE(temp$p.value < 0.05), .Options$DHARMaSignalColor, "black" ), bty="n")
  }

}



#' Generic res ~ pred scatter plot with spline or quantile regression on top
#'
#' The function creates a generic residual plot with either spline or quantile regression to highlight patterns in the residuals. Outliers are marked in star/asterisk form and highlighted in red if the outlier test is significant.
#'
#' @param simulationOutput an object, usually a DHARMa object, from which residual values can be extracted. Alternatively, a vector with residuals or a fitted model can be provided, which will then be transformed into a DHARMa object.
#' @param form optional predictor(s) against which the residuals should be plotted. Default is to use the predicted(simulationOutput). Recommended to specify as formula. Use \code{form = ~.} to plot against all predictors. See details.
#' @param quantreg whether to perform a quantile regression based on [testQuantiles] or a smooth spline around the mean. Default NULL chooses T for nObs < 10000, and F otherwise.
#' @param rank if T, the values provided in form will be rank transformed. This will usually make patterns easier to spot visually, especially if the distribution of the predictor is skewed. If form is a factor, this has no effect.
#' @param asFactor should a numeric predictor provided in form be treated as a factor. Default is to choose this for < 10 unique values, as long as enough predictions are available to draw a boxplot.
#' @param smoothScatter if T, a smooth scatter plot will plotted instead of a normal scatter plot. This makes sense when the number of residuals is very large. Default NULL chooses T for nObs > 10000, and F otherwise.
#' @param quantiles for a quantile regression, which quantiles should be plotted. Default is 0.25, 0.5, 0.75.
#' @param absoluteDeviation if T, switch from displaying normal quantile residuals to absolute deviation from the mean expectation of 0.5 (calculated as 2 * abs(res - 0.5)). The purpose of this is to test explicitly for heteroskedasticity, see details.
#' @param ... additional arguments to plot / boxplot. Ignored if several panels are plotted.
#' @details The function plots residuals against a predictor (by default against the fitted value, extracted from the DHARMa object, or any other predictor). The shaded gray areas indicate 95% confidence intervals of the quantile estimates (1.96 * standard error).
#'
#' Outliers are drawn if simulationOutput is a DHARMa object and highlighted in red if the outlier test is significant (for information on definition and interpretation of outliers, see [testOutliers]). See the note below to change the highlighting color of the outliers.
#'
#' To provide a visual aid for detecting deviations from uniformity in the y-direction, the plot function calculates an (optional) quantile regression of the residuals, by default for the 0.25, 0.5 and 0.75 quantiles. Since the residuals should be uniformly distributed for a correctly specified model, the theoretical expectations for these regressions are straight lines at 0.25, 0.5 and 0.75, shown as dashed black lines on the plot. However, even for a perfect model, some deviation from these expectations is to be expected by chance, especially if the sample size is small. The function therefore tests whether the deviation of the fitted quantile regression from the expectation is significant, using [testQuantiles]. If so, the significant quantile regression is highlighted in red (as default) and a warning is displayed in the plot. See the note below to change the color of significant quantile lines.
#'
#' Overdispersion typically manifests itself as Q1 (0.25) deviating towards 0 and Q3 (0.75) deviating towards 1. Heteroskedasticity manifests itself as non-parallel quantile lines. To diagnose heteroskedasticity and overdispersion, it can be helpful to additionally plot the absolute deviation of the residuals from the mean expectation of 0.5, using the option absoluteDeviation = T. In this case, we would again expect Q1-Q3 quantile lines at 0.25, 0.5, 0.75, but greater dispersion (also locally in the case of heteroskedasticity) always manifests itself in deviations towards 1.
#'
#' The quantile regression can take some time to calculate, especially for larger datasets. For this reason, quantreg = F can be set to generate a smooth spline instead. This is the default for n > 10000.
#'
#' If form is specified as a formula, e.g. \code{form = ~ your_predictor}, NAs will be handled automatically (recommended). If \code{form = ~.}, separate plots for all predictors in the model are produced. If \code{form = ~ predictor1 + predictor2}, a separate plot for each specified predictor is produced. If an additional grouping variable is specified, e.g. \code{form = ~ predictor|group}, a separate plot for the predictor within each grouping level is produced. Be careful with this command: if you have many levels, the plot may not display nicely. If you are interested in a specific group, you can use \code{form = ~ predictor|group == "group_level"}, and for several groups \code{form = ~ predictor|group \%in\% c("level1", "level2")}, which produces a separate plot for each of these levels. If form is **not** a formula, e.g. \code{form = data$predictor}, NAs are **not** handled automatically. For phyr and gamm4$mer models, you need to specify form in this way.
#'
#' If the predictor is a factor, a boxplot will be plotted instead of a scatter plot. The distribution for each factor level should be uniformly distributed, so the box should go from 0.25 to 0.75, with the median line at 0.5 (within-group). To test if deviations from those expectations are significant, KS-tests per group and a Levene test for homogeneity of variances are performed. See [testCategorical] for details.
#'
#' @note If nObs > 10,000, the scatter plot is replaced by graphics::smoothScatter().
#'
#' The color for highlighting outliers and quantile lines/splines with significant tests can be changed by setting \code{options(DHARMaSignalColor = "red")} to a different color. See \code{getOption("DHARMaSignalColor")} for the current setting. This is convenient for a color-blind friendly display, since red and black are difficult for some people to distinguish.
#'
#' @return If quantile tests are performed, the function returns them invisibly. If several panels are plotted, the function returns NULL.
#'
#' @seealso [plotQQunif], [testQuantiles], [testOutliers]
#' @example inst/examples/plotResidualsHelp.R
#' @export
plotResiduals <- function(simulationOutput, form = NULL, quantreg = NULL,
                          rank = TRUE, asFactor = NULL, smoothScatter = NULL,
                          quantiles = c(0.25, 0.5, 0.75),
                          absoluteDeviation = FALSE, ...){


  ##### Checks #####

  a <- list(...)
  yAxis = ifelse(absoluteDeviation == TRUE, "Residual spread [2*abs(res - 0.5)]", "DHARMa residual")
  a$ylab = checkDots("ylab", yAxis , ...)
  # all.vars only for formulas, as it returns character(0) for vectors
  a$xlab = checkDots("xlab", if(is.null(form)) "Model predictions"
                     else if(inherits(form, "formula")) paste(unique(all.vars(form)), collapse = ", ")
                     else gsub(".*[$]|^~","", paste(deparse(substitute(form)), collapse = "")), ...)
  a$main = checkDots("main", NULL, ...)

  simOut <- simulationOutput
  simulationOutput = ensureDHARMa(simulationOutput, convert = TRUE)
  res = simulationOutput$scaledResiduals

  if(absoluteDeviation == TRUE){
    res = 2 * abs(res - 0.5)
  }

  if(inherits(form, "DHARMa"))stop("DHARMa::plotResiduals > argument form cannot be of class DHARMa. Note that the syntax of plotResiduals has changed since DHARMa 0.3.0. See ?plotResiduals.")

  ##### form #####
  checkForm = substitute(form)
  if(!is.null(checkForm)) {
    if (!inherits(form, "formula")) {
      predictor = form # go back to old default
      group = NULL
      if(is.null(predictor)) stop("DHARMA: unable to find specified predictor variable.")

    } else {

      if(simulationOutput$modelClass == "communityPGLMM") stop("DHARMa: to use plotResiduals with phyr models, please return to the old DHARMa default, e.g. form = your_data$your_predictor.")

      if(form == "~.") {
        predictorNames = getPredictorNames(simulationOutput$fittedModel)

        # issue #536: remove "(weights)" from predictorNames
        if("(weights)" %in% predictorNames) {predictorNames = predictorNames[!predictorNames %in% "(weights)"]}
        return(plotResidualsPanels(
          simulationOutput = simulationOutput,
          predictorNames = predictorNames,
          predictorType = "predictor",
          form = form,
          quantreg = quantreg,
          rank = rank,
          asFactor = asFactor,
          smoothScatter = smoothScatter,
          quantiles = quantiles,
          absoluteDeviation = absoluteDeviation,
          ...
        ))}

      # if there is more than 1 predictor, check if form is specified either
      # with "|" (plot residuals within a certain group)
      # or "+" (plot residuals for multiple predictors in separate panels via plotResidualsPanels)

      predictors = getFormulaPredictors(simulationOutput = simulationOutput, formula = form)

      if(length(predictors) > 1) {
        operators = all.names(form[[2]])

        if("|" %in% operators && "+" %in% operators) stop("DHARMa: Detected both + and | as operators. Please choose one or the other. See ?plotResiduals.")

        # for formulas with +, create a separate residual plot for each predictor
        if("+" %in% operators) {
          predictorNames = names(predictors)

          return(plotResidualsPanels(
            simulationOutput = simulationOutput,
            predictorNames = predictorNames,
            predictorType = "predictor",
            form = form,
            quantreg = quantreg,
            rank = rank,
            asFactor = asFactor,
            smoothScatter = smoothScatter,
            quantiles = quantiles,
            absoluteDeviation = absoluteDeviation,
            ...
          ))

        }

        # for formulas with |, get predictor and group variables
        predictor = if (length(predictors) >= 1) predictors[[1]] else NULL
        group = if (length(predictors) >= 2) predictors[[2]] else NULL

        # if form has just one predictor, make the standard plot for that predictor
      } else {
        predictor = if (length(predictors) >= 1) predictors[[1]] else NULL
        group = NULL
      }

      if(is.null(predictor)) stop("DHARMA: unable to extract specified predictor variable from the data frame that was used to fit the model. Further note: if you are using a gamm4 model, please use form = your_data$your_predictor instead of form = ~ your_predictor.")
    }
  } else {
    predictor = NULL
    group = NULL
  }

  pred = ensurePredictor(simulationOutput, predictor)
  group = if(!is.null(group)) {ensurePredictor(simulationOutput, group)}

  # if group is not NULL, get predictor and residuals belonging to specified group level OR create residual plot for each group level
  if(!is.null(group)) {
    groupLevel = tryCatch(eval(form[[2]][[3]][[3]], environment(form)), error = function(e) NULL)
    if(!is.null(groupLevel) && !deparse(form[[2]][[3]][[1]]) %in% c("==", "%in%")) stop("DHARMa: to select group levels, use == or %in%, e.g. form = ~x | group %in% c(\"a\", \"b\").")
    if(!is.null(groupLevel) && (length(groupLevel) == 0 || !all(groupLevel %in% levels(factor(group))))) stop("DHARMa: Unable to find specified group level(s).")

    # one panel per group level, for all or for several selected levels (#596)
    if(length(groupLevel) != 1) {
      predictorNames = levels(factor(group))
      if(!is.null(groupLevel)) {
        predictorNames = predictorNames[predictorNames %in% groupLevel]
        form[[2]][[3]] = form[[2]][[3]][[2]] # ~x | group %in% c(...) -> ~x | group
      }

      return(plotResidualsPanels(
        simulationOutput = simulationOutput,
        predictorNames = predictorNames,
        predictorType = "groupLevel",
        form = form,
        quantreg = quantreg,
        rank = rank,
        asFactor = asFactor,
        smoothScatter = smoothScatter,
        quantiles = quantiles,
        absoluteDeviation = absoluteDeviation,
        ...
      ))
    }

    pred = pred[group == groupLevel]
    res = res[group == groupLevel]
  }




  ##### Rank transform and factor conversion#####

  if(!is.factor(pred)){

    if (rank == TRUE){
      pred = rankTransform(pred)
      a$xlim = checkDots("xlim", c(0,1), ...)
      a$xlab = paste(a$xlab, "(rank transformed)")
    }

    nuniq = length(unique(pred))
    ndata = length(pred)
    if(is.null(asFactor)) asFactor = (nuniq == 1) | (nuniq < 10 & ndata / nuniq > 10)
    if (asFactor) pred = factor(pred)
  }

  ##### Residual scatter plots #####

  if(is.null(quantreg)) {
    if (length(res) > 10000) {
      quantreg = FALSE
      message("plotResiduals() for datasets larger than 10,000 displays a spline instead of quantile regression lines for the sake of speed. To switch back to quantile regression lines, use the argument quantreg = T and have in mind that the function may take a while to compute and display the lines.")
    }
    else quantreg = TRUE
  }

  switchScatter = 10000
  if(is.null(smoothScatter)) if (length(res) > switchScatter) smoothScatter = TRUE else smoothScatter = FALSE

  blackcol = rgb(0,0,0, alpha = max(0.1, 1 - 3 * length(res) / switchScatter))

  # Note to self: wrapped in do.call because of the check dots, needs to be consolidate, e.g. for testCategorical

  # categorical plot
  if(is.factor(pred)){
    simulationOutput$scaledResiduals = res
    testCategorical(simulationOutput = simulationOutput, catPred = pred,
                    quantiles = quantiles, xlab = a$xlab, ...)

  } else{

    # color/shape outliers according to significance of outlier test, related to issue #453
    outlier <- res == 0 | res == 1
    if(is.vector(simOut)) {
      message("Outliers will be not displayed in the plot when simulationOutput is not a DHARMa object.")
      defaultCol = blackcol
      defaultPch = 1
    } else {
      p.outliers <- testOutliers(simOut, plot = F)$p.value
      defaultPch = ifelse(outlier==TRUE, 8, 1)
      if(p.outliers < 0.05){
        defaultCol <- ifelse(outlier == TRUE, .Options$DHARMaSignalColor, blackcol)
      } else{defaultCol = blackcol}
    }

    # smooth scatter
    if (smoothScatter == TRUE) {
      do.call(graphics::smoothScatter, append(list(x = pred, y = res ,
                                                   ylim = c(0,1), axes = FALSE,
                                                   colramp = colorRampPalette(c("white", "darkgrey"))),
                                              a[names(a) != "main"]))
      if(!is.vector(simOut)){
      points(pred[outlier], res[outlier], pch = 8, cex = 0.5,
             col = ifelse(p.outliers < 0.05, .Options$DHARMaSignalColor, "black"))
    }
      axis(1)
      axis(2, at=c(0, quantiles, 1))
    }
    # normal plot
    else{
      a$col = checkDots("col", defaultCol, ...)
      a$pch = checkDots("pch", defaultPch, ...)
      do.call(plot, append(list(res ~ pred, ylim = c(0,1), axes = FALSE), a[names(a) != "main"]))

      axis(1)
      axis(2, at=c(0, quantiles, 1))
    }
  }
  ##### Quantile regressions #####

  if(is.null(a$main)) {main = ifelse(is.null(form), paste(yAxis, "vs. predicted"), paste(yAxis, "vs. predictor"))} else {main = a$main}
  out = NULL

  if(is.numeric(pred)){
    if(quantreg == FALSE){
      title(main = main, cex.main = 0.8)
      abline(h = 0.5, col = "black", lwd = 0.5, lty = 2)
      try({
        lines(smooth.spline(pred, res, df = 10), lty = 2, lwd = 2,
              col = "black")
      }, silent = TRUE)

    }else{

      out = testQuantiles(res, pred, quantiles = quantiles, plot = FALSE,
                          rank = rank)

      if(is.na(out$p.value)){
        main = paste(main, "Some quantile regressions failed", sep = "\n")
        maincol = .Options$DHARMaSignalColor
      } else{
        if(any(out$pvals < 0.05, na.rm = TRUE)){
          main = paste(main, "Quantile deviations detected (red curves)", sep ="\n")
          if(out$p.value <= 0.05){
            main = paste(main, "Combined adjusted quantile test significant", sep ="\n")
          } else {
            main = paste(main, "Combined adjusted quantile test n.s.", sep ="\n")
          }
          maincol = .Options$DHARMaSignalColor
        } else {
          main = paste(main, "No significant problems detected", sep ="\n")
          maincol = "black"
        }
      }

      title(main = main, cex.main = 0.8,
            col.main = maincol, line = 1)

      for(i in 1:length(quantiles)){

        lineCol = ifelse(out$pvals[i] <= 0.05 & !(is.na(out$pvals[i])), .Options$DHARMaSignalColor, "black")
        filCol = ifelse(out$pvals[i] <= 0.05 & !(is.na(out$pvals[i])), "#FF000040", "#00000020")

        abline(h = quantiles[i], col = lineCol, lwd = 0.5, lty = 2)
        polygon(c(out$predictions$pred, rev(out$predictions$pred)),
                c(out$predictions[,2*i] - out$predictions[,2*i+1], rev(out$predictions[,2*i] + out$predictions[,2*i+1])),
                col = "#00000020", border = FALSE)
        lines(out$predictions$pred, out$predictions[,2*i], col = lineCol, lwd = 2)
      }

    }
  }
  invisible(out)
}


#plotConventionalResiduals(fittedModel)


#' Conventional residual plot
#'
#' Convenience function to draw conventional residual plots
#'
#' @param fittedModel a fitted model object
#' @export
plotConventionalResiduals <- function(fittedModel){
  opar <- par(mfrow = c(1,3), oma = c(0,1,2,1))
  on.exit(par(opar))
  plot(predict(fittedModel), resid(fittedModel, type = "deviance"), main = "Deviance" , ylab = "Residual", xlab = "Predicted")
  plot(predict(fittedModel), resid(fittedModel, type = "pearson") , main = "Pearson", ylab = "Residual", xlab = "Predicted")
  plot(predict(fittedModel), resid(fittedModel, type = "response") , main = "Raw residuals" , ylab = "Residual", xlab = "Predicted")
  mtext("Conventional residual plots", outer = TRUE)
}



#' Create multiple residual plots simultaneously (deprecated)
#'
#' DEPRECATED, use [plotResiduals] with `form = ~.`, `~a + b`, `~x | group` or `~x | group %in% c(...)` instead
#'
#' @param simulationOutput an object with simulated residuals created by [simulateResiduals].
#' @param predictorNames names of the predictors / group levels to be plotted.
#' @param predictorType whether multiple plots should be created based on different predictor variables (predictor) or a single predictor and each corresponding group level (groupLevel).
#' @param form optional predictor (and grouping variable) against which the residuals should be plotted.
#' @param ... further options for [plotResiduals].
#' @note This function is deprecated. Use [plotResiduals]
#' @export
plotResidualsAll <- function(simulationOutput, predictorNames, predictorType = c("predictor", "groupLevel"), form = NULL, ...){
  message("plotResidualsAll is deprecated, please switch your code to plotResiduals() with argument form, see ?plotResiduals")
  plotResidualsPanels(simulationOutput, predictorNames, match.arg(predictorType), form, ...)
}

# internal function of plotResiduals, plots one panel per predictor or group level
plotResidualsPanels <- function(simulationOutput, predictorNames, predictorType = c("predictor", "groupLevel"), form = NULL, quantreg = NULL,
                             rank = TRUE, asFactor = NULL, smoothScatter = NULL,
                             quantiles = c(0.25, 0.5, 0.75),
                             absoluteDeviation = FALSE, ...){

  opar = par(no.readonly = TRUE)
  on.exit(par(opar))

  # remove duplicate predictors, e.g. due to quadratic effects (fixes issue #536)
  # only for predictors, group levels are not variable names (issue #573)
  if(predictorType == "predictor"){
    Vars = unname(sapply(predictorNames, function(x) all.vars(formula(paste("~", x)))[1]))
    predictorNames = predictorNames[!duplicated(Vars)]
  }

  # get number of panels needed (copied from BayesianTools)
  numPredictors = length(predictorNames)
  if (numPredictors <= 0) stop("Unable to extract predictor names from model.")
  lower = floor(sqrt(numPredictors))
  upper = ceiling(sqrt(numPredictors))

  if (lower == upper) {
    mfrow = c(lower, lower)
  } else if (lower * upper >= numPredictors) {
    mfrow = c(lower, upper)
  } else {
    mfrow = c(upper, upper)
  }

  par(mfrow = mfrow)

  if(predictorType == "predictor"){
    # create residual plot for multiple predictors (additional arguments in ... are ignored here)
    for(i in 1:length(predictorNames)){
      form = eval(formula(paste("~", predictorNames[i])))
      plotResiduals(simulationOutput,
                    form = form,
                    quantreg = quantreg,
                    rank = rank,
                    asFactor = asFactor,
                    smoothScatter = smoothScatter,
                    quantiles = quantiles,
                    absoluteDeviation = absoluteDeviation,
                    # create the correct xlab for poly()-syntax (related to issue #536)
                    xlab = paste(unique(all.vars(form)), collapse = ", "))
    }
  }

  if(predictorType == "groupLevel"){
    # create residual plot for each group level of a predictor
    for(i in 1:length(predictorNames)){
      newForm = paste("~", form, "==", deparse(predictorNames[i]))[[2]]

      plotResiduals(simulationOutput,
                    form = formula(newForm),
                    quantreg = quantreg,
                    rank = rank,
                    asFactor = asFactor,
                    smoothScatter = smoothScatter,
                    quantiles = quantiles,
                    absoluteDeviation = absoluteDeviation,
                    xlab = newForm)
    }
  }

}

Try the DHARMa package in your browser

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

DHARMa documentation built on Nov. 7, 2026, 5:08 p.m.