R/gg.matrix.R

Defines functions gg.matrix

Documented in gg.matrix

#' Create Matrix of ggplot2 Plots
#'
#' This function creates a matrix of ggplot2 plots.
#'
#' @param ...             an expression indicating the names of the ggplot2 plot
#'                        or a list of ggplot2 plots to be put into the matrix.
#' @param ncol            a numeric value indicating the number of columns. Note
#'                        that at least one of the argument \code{ncol} or \code{nrow}
#'                        needs to be specified.
#' @param nrow            a numeric value indicating the number of rows Note
#'                        that at least one of the argument \code{ncol} or \code{nrow}
#'                        needs to be specified.
#' @param byrow           logical: if \code{TRUE} (default), the plots are ordered
#'                        by rows.
#' @param strip.lab       a character vector specifying the strip labels for the
#'                        ggplot2 plots specified in the argument \code{...}.
#'                        Note that the length of the character vector needs to
#'                        match the number of plots specified in the argument
#'                        \code{...}.
#' @param strip.xlab      a character vector specifying the strip labels for the
#'                        x axis. Note that the length of the character vector
#'                        needs to match the argument \code{ncol}.
#' @param strip.ylab      a character vector specifying the strip labels for the
#'                        y axis. Note that the length of the character vector
#'                        needs to match the argument \code{nrow}.
#' @param strip.show      logical: if \code{TRUE}, each plot's strip label will
#'                        be shown. Note that the default setting \code{NULL}
#'                        will show strip labels on the top and right plots only.
#' @param strip.labels    a character string specifying on which side the plots
#'                        strip labels are printed, i.e., \code{"topright"} (default)
#'                        for printing labels on the top and right part of the
#'                        plot matrix, \code{"bottomright"} for printing labels
#'                        on the bottom and right part of the plot matrix,
#'                        \code{"topleft"} for printing labels on the top and
#'                        left part of the plot matrix, or \code{"bottomleft"}
#'                        for printing labels on the bottom and left part of the
#'                        plot matrix.
#' @param title           a character string specifying the title of the plot.
#' @param xlab            a character string specifying the x label of the plot.
#' @param ylab            a character string specifying the y label of the plot.
#' @param axis.labels     a character string specifying which plot axis labels
#'                        are printed, i.e., \code{"both"} (default) for printing
#'                        axis labels on the x and y part of the plot matrix,
#'                        \code{"x"} for printing the axis label on the x part of
#'                        the plot matrix, \code{"y"} for printing axis label on
#'                        y part of the plot matrix, or \code{"none"} for not printing
#'                        any axis labels of the plot matrix.
#' @param legend          a numeric vector of length 2 specifying the location
#'                        of the plot to use the legend for the plot matrix's
#'                        legend, or a numeric value specifying the location of
#'                        a plot according to the display order. By default, the
#'                        plot displays the legend of the first plot.
#' @param labeller        labeller for facets.
#' @param x.prop          a numeric vector specifying how much area is given for
#'                        each plot in the columns.
#' @param y.prop          a numeric vector specifying how much area is given for
#'                        each plot in the rows.
#' @param title.text.size a numeric value (default: \code{10}) indicating
#'                        the \code{size} argument in the \code{element_text}
#'                        function for the \code{plot.title} argument, i.e.
#'                        \code{theme(plot.title = element_text(size = title.text.size))}
#' @param strip.text.size a numeric value (default: \code{10}) indicating
#'                        the \code{size} argument in the \code{element_text} function
#'                        for the \code{strip.text} argument, i.e.
#'                        \code{theme(strip.text = element_text(size = strip.text.size))}
#' @param axis.title.size a numeric value (default: \code{10}) indicating
#'                        the \code{size} argument in the \code{element_text} function
#'                        for the \code{axis.title} argument, i.e.
#'                        \code{theme(axis.title = element_text(size = axis.title.size))}
#' @param axis.text.size  a numeric value (default: \code{10}) indicating
#'                        the \code{size} argument in the \code{element_text} function
#'                        for the \code{axis.text} argument, i.e.
#'                        \code{theme(axis.text = element_text(size = axis.text.size))}
#' @param filename        a character string indicating the \code{filename}
#'                        argument including the file extension in the \code{ggsave}
#'                        function. Note that one of \code{".eps"}, \code{".ps"},
#'                        \code{".tex"}, \code{".pdf"} (default),
#'                        \code{".jpeg"}, \code{".tiff"}, \code{".png"},
#'                        \code{".bmp"}, \code{".svg"} or \code{".wmf"} needs
#'                        to be specified as file extension in the \code{filename}
#'                        argument. Note that plots can only be saved when
#'                        \code{plot = TRUE}.
#' @param width           a numeric value indicating the \code{width} argument
#'                        (default is the size of the current graphics device)
#'                        in the \code{ggsave} function.
#' @param height          a numeric value indicating the \code{height} argument
#'                        (default is the size of the current graphics device)
#'                        in the \code{ggsave} function.
#' @param dpi             a numeric value indicating the \code{dpi} argument
#'                        (default: \code{600}) in the \code{ggsave} function.
#' @param check           logical: if \code{TRUE} (default), argument specification
#'                        is checked.
#' @param plot            logical: if \code{TRUE} (default), the matrix of ggplot2
#'                        plot is drawn.
#'
#' @author
#' Takuya Yanagida
#'
#' @references
#' Schloerke, B., Cook, D., Larmarange, J., Briatte, F., Marbach, M., Thoen, E.,
#' Elberg, A., & Crowley, J. (2025). \emph{GGally: Extension to 'ggplot2'}. R
#' package version 2.4.0. Retrieved from https://CRAN.R-project.org/package=GGally
#'
#' @note This function uses the function \code{ggmatrix} from the \pkg{GGally}
#' package by Barret Schloerke, Di Cook, Joseph Larmarange, Francois Briatte,
#' Moritz Marbach, Edwin Thoen, Amos Elberg, and Jason Crowley (2025).
#'
#' @return
#' Returns an object of class \code{misty.object}, which is a list with following
#' entries:
#' \item{\code{call}}{function call}
#' \item{\code{type}}{type of analysis}
#' \item{\code{args}}{specification of function arguments}
#' \item{\code{plot}}{ggplot2 object}
#'
#' @export
#'
#' @examples
#' \dontrun{
#' # Load ggplot2 package
#' library(ggplot2)
#'
#' # Generate some random plots
#' p1 <- ggplot(mtcars, aes(mpg, hp, color = disp)) + geom_point()
#' p2 <- ggplot(mtcars, aes(mpg, drat, color = disp)) + geom_point()
#' p3 <- ggplot(mtcars, aes(mpg, wt, color = disp)) + geom_point()
#' p4 <- ggplot(mtcars, aes(mpg, qsec, color = disp)) + geom_point()
#'
#' #————————————————————————————————————————————————————————————————————————————
#' # Matrix of ggplot2 Plots
#'
#' # Example 1a: Arrange plots in four rows
#' gg.matrix(p1, p2, p3, p4, nrow = 4)
#'
#' # Example 1b: Alternative specification using a list of plots
#' gg.matrix(list(p1, p2, p3, p4), nrow = 4)
#'
#' # Example 1c: Arrange plots in two rows and four columns
#' gg.matrix(p1, p2, p3, p4, nrow = 2, ncol = 2)
#'
#' # Example 1d: Alternative specification using a list of plots
#' gg.matrix(list(p1, p2, p3, p4), nrow = 2, ncol = 2)
#'
#' #————————————————————————————————————————————————————————————————————————————
#' # 'strip.lab', 'strip.xlab', and 'strip.ylab' Arguments
#'
#' # Example 2a: Strip labels for the y axis
#' gg.matrix(p1, p2, p3, p4, nrow = 4,
#'           strip.ylab = c("mpg - hp", "mpg - drat", "mpg - wt", "qmpg - sec"))
#'
#' # Example 2b: Strip labels for the x axis
#' gg.matrix(p1, p2, p3, p4, ncol = 4,
#'           strip.xlab = c("mpg - hp", "mpg - drat", "mpg - wt", "qmpg - sec"))
#'
#' # Example 2c: Strip label for each plot
#' gg.matrix(p1, p2, p3, p4, nrow = 2, ncol = 2, strip.show = TRUE,
#'           strip.lab = c("mpg - hp", "mpg - drat", "mpg - wt", "qmpg - sec"))
#'
#' # Example 2d: Strip label for each plot and for the y axis
#' gg.matrix(p1, p2, p3, p4, nrow = 2, ncol = 2,
#'           strip.ylab = c("A", "B"), strip.show = TRUE,
#'           strip.lab = c("mpg - hp", "mpg - drat", "mpg - wt", "qmpg - sec"))
#'
#' #————————————————————————————————————————————————————————————————————————————
#' # 'x.prop' and 'y.prop' Arguments
#'
#' # Example 3: Modify area given for each plot in the columns and rows
#' gg.matrix(p1, p2, p3, p4, nrow = 2, ncol = 2,
#'           x.prop = c(0.4, 0.6), y.prop = c(0.80, 0.20))
#'
#' #————————————————————————————————————————————————————————————————————————————
#' # 'strip.show' Argument
#'
#' # Load data set "tips" in the GGally package
#' data("tips", package = "GGally")
#'
#' # Create four plots depending on 'smoker' (No/Yes) and 'sex' (Female/Male)
#' plots <- tapply(tips, paste0(tips$smoker, tips$sex), function(y) {
#'
#'   ggplot(y, aes(total_bill, tip)) + geom_point() + facet_grid(time ~ day)
#'
#' })
#'
#' # Example 4a: Show strip labels in the top row and the right most column
#' gg.matrix(plots, nrow = 2, ncol = 2, strip.ylab = c("Female", "Male"),
#'           strip.xlab = c("Non Smoker", "Smoker"))
#'
#' # Example 4b: Show all strip labels
#' gg.matrix(plots, nrow = 2, ncol = 2, strip.ylab = c("Female", "Male"),
#'           strip.xlab = c("Non Smoker", "Smoker"), strip.show = TRUE)
#'
#' # Example 4c: Do not show any strip labels
#' gg.matrix(plots, nrow = 2, ncol = 2, strip.ylab = c("Female", "Male"),
#'           strip.xlab = c("Non Smoker", "Smoker"), strip.show = FALSE)
#'
#' #————————————————————————————————————————————————————————————————————————————
#' # Additional ggplot2 Arguments
#'
#' # Create matrix of ggplot2 plots
#' p <- gg.matrix(p1, p2, p3, p4, nrow = 2, ncol = 2, plot = FALSE)
#'
#' # Example 5: Additional ggplot2 arguments
#' p$plot +
#'  theme_bw() +
#'  theme(legend.position = "bottom", legend.box.margin = margin(-10, 0, 0, 0))
#'
#' #————————————————————————————————————————————————————————————————————————————
#' # Save Plot
#'
#' # Example 6: Save plot as PNG file
#' gg.matrix(p1, p2, p3, p4, nrow = 4, strip.ylab = c("hp", "drat", "wt", "qsec"),
#'           filename = "Plot_Matrix.png", width = 7, height = 10)
#' }
gg.matrix <- function(..., ncol = 1, nrow = 1, byrow = TRUE, strip.lab = NULL,
                      strip.xlab = NULL, strip.ylab = NULL, strip.show = NULL,
                      strip.labels = "topright", title = NULL, xlab = NULL, ylab = NULL,
                      axis.labels = c("both", "x", "y", "none"), legend = 1,
                      labeller = NULL, x.prop = NULL, y.prop = NULL,
                      title.text.size = 10, strip.text.size = 10,
                      axis.title.size = 10, axis.text.size = 10,
                      filename = NULL, width = NA, height = NA, dpi = 600,
                      check = TRUE, plot = TRUE) {

  #_____________________________________________________________________________
  #
  # Plots ——————————————————————————————————————————————————————————————————————

  # Extract ggplot objects
  plots <- list(...) |> (\(p) if (isTRUE(length(p) == 1L)) { return(p[[1L]]) } else { return(p) })()

  # Check if ggplot objects
  if (isTRUE(any(!sapply(plots, ggplot2::is_ggplot)))) { stop(paste0("Please specify a list of ggplot objects or multiple ggplot objects for the argument '...': ", paste(which(!sapply(plots, ggplot2::is.ggplot)), collapse = ", ")), call. = FALSE) }

  # Check if more than one ggplot object
  if (isTRUE(length(plots) == 1L)) { stop("Please specify more than one ggplot object for the argument '...'.", call. = FALSE) }

  #_____________________________________________________________________________
  #
  # Input Check ————————————————————————————————————————————————————————————————

  .check.input(logical = c("byrow", "strip.show", "plot"), numeric = list(ncol = 1L, nrow = 1L, title.text.size = 1L, strip.text.size = 1L, axis.title.size = 1L, axis.text.size = 1L, width = 1L, height = 1L, dpi = 1L), character = list(title = 1L, xlab = 1L, ylab = 1L, filename = 1L), s.character = list(strip.labels = c("topright", "bottomright", "topleft", "bottomleft"), axis.labels = c("both", "x", "y", "none")),
               package = "GGally", envir = environment(), input.check = check)

  #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  ## Additional Checks ####

  if (isTRUE(check)) {

    #—————————————————————————————————————— #
    ### 'nrow' and 'ncol' ####

    if (isTRUE(nrow == 1L && ncol == 1L)) { stop("Please specify at least one of the arguments 'nrow' and 'ncol'.", call. = FALSE) }

    #—————————————————————————————————————— #
    ### strip.lab ####

    if (isTRUE(!is.null(strip.lab))) { if (isTRUE(length(strip.lab) != length(plots))) { stop("The length of the character vector specified in the argument 'strip.lab' does not match the number of plots specified in the argument '...'.", call. = FALSE) } }

    #—————————————————————————————————————— #
    ### strip.xlab ####

    if (isTRUE(!is.null(strip.xlab))) {

      if (isTRUE(is.null(nrow))) { stop("Please specify the argument 'nrow' when specifying the argument 'strip.xlab'.", call. = FALSE) }

      if (isTRUE(length(strip.xlab) != ncol)) { stop("The length of the character vector specified in the argument 'strip.xlab' does not match with the argument 'nrow'.", call. = FALSE) }

    }

    #—————————————————————————————————————— #
    ### strip.ylab ####

    if (isTRUE(!is.null(strip.ylab))) {

      if (isTRUE(is.null(ncol))) { stop("Please specify the argument 'nrow' when specifying the argument 'strip.ylab'.", call. = FALSE) }

      if (isTRUE(length(strip.ylab) != nrow)) { stop("The length of the character vector specified in the argument 'strip.ylab' does not match with the argument 'ncol'.", call. = FALSE) }

    }

    #—————————————————————————————————————— #
    ### 'x.prop' and 'y.prop' ####

    # 'x.prop' Argument
    if (isTRUE(!is.null(x.prop) & length(x.prop) != ncol)) { stop("The length of the numeric vector specified in the argument 'x.prop' does not match with the argument 'ncol'.", call. = FALSE) }

    # 'y.prop' Argument
    if (isTRUE(!is.null(y.prop) & length(y.prop) != nrow)) { stop("The length of the numeric vector specified in the argument 'y.prop' does not match with the argument 'nrow'.", call. = FALSE) }

  }

  #_____________________________________________________________________________
  #
  # Arguments ——————————————————————————————————————————————————————————————————

  #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  ## 'axis.labels' Argument ####

  if (isTRUE(all(c("both", "x", "y", "none") %in% axis.labels))) { axis.labels <- "both" }

  switch(axis.labels,
         "both" = {

           axis.labels.x <- TRUE
           axis.labels.y <- TRUE

         }, "x" = {

           axis.labels.x <- TRUE
           axis.labels.y <- FALSE

         }, "y" = {

           axis.labels.x <- FALSE
           axis.labels.y <- TRUE

         }, "none" = {

           axis.labels.x <- FALSE
           axis.labels.y <- FALSE

         })

  #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  ## 'strip.labels' Argument ####

  switch(strip.labels,
         "topright" = {

           strip.labels.switch <- NULL

         }, "bottomright" = {

           strip.labels.switch <- "x"

         }, "topleft" = {

           strip.labels.switch <- "y"

         }, "bottomleft" = {

           strip.labels.switch <- "both"

         })

  #_____________________________________________________________________________
  #
  # Main Function ——————————————————————————————————————————————————————————————

  #—————————————————————————————————————— #
  ### Add Strip Text ####

  if (isTRUE(!is.null(strip.lab))) {

    for (i in seq_along(plots)) { plots[[i]] <- plots[[i]] + data.frame(plots[[i]]$data, strip.lab = strip.lab[i]) + ggplot2::facet_grid( ~ strip.lab) }

  }

  #—————————————————————————————————————— #
  ### Create Plot Matrix ####

  plot.matrix <- GGally::ggmatrix(plots, ncol = ncol, nrow = nrow, xAxisLabels = strip.xlab, yAxisLabels = strip.ylab, title = title, xlab = xlab, ylab = ylab, byrow = byrow, showStrips = strip.show,
                                  showXAxisPlotLabels = axis.labels.x, showYAxisPlotLabels = axis.labels.y, labeller = labeller, switch = strip.labels.switch, xProportions = x.prop, yProportions = y.prop,
                                  progress = FALSE, data = NULL, gg = NULL, legend = legend) +
                   ggplot2::theme(plot.title = ggplot2::element_text(size = title.text.size, hjust = 0.5),
                                  strip.text = ggplot2::element_text(size = strip.text.size),
                                  axis.title = ggplot2::element_text(size = axis.title.size),
                                  axis.text  = ggplot2::element_text(size = axis.text.size))

  #_____________________________________________________________________________
  #
  # Return Object ——————————————————————————————————————————————————————————————

  object <- list(call = match.call(),
                 type = "gg.matrix",
                 args = list(plots = plots, ncol = ncol, nrow = nrow, strip.lab = strip.lab, strip.xlab = strip.xlab, strip.ylab = strip.ylab, title = title, xlab = xlab, ylab = ylab, byrow = byrow, axis.labels = axis.labels, labeller = labeller, strip.labels = strip.labels, x.prop = x.prop, y.prop = y.prop, legend = legend, title.text.size = title.text.size, strip.text.size = strip.text.size, axis.title.size = axis.title.size, axis.text.size = axis.text.size, filename = filename, width = width, height = height, dpi = dpi),
                 plot = plot.matrix)

  class(object) <- "misty.object"

  #_____________________________________________________________________________
  #
  # Save Plot ——————————————————————————————————————————————————————————————————

  if (isTRUE(!is.null(filename))) { suppressWarnings(suppressMessages(ggplot2::ggsave(filename = filename, plot = plot.matrix, width = width, height = height, dpi = dpi))) }

  #_____________________________________________________________________________
  #
  # Output —————————————————————————————————————————————————————————————————————

  if (isTRUE(plot)) { print(object, check = FALSE) }

  return(invisible(object))

}

#_______________________________________________________________________________

Try the misty package in your browser

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

misty documentation built on Nov. 24, 2026, 5:06 p.m.