R/plot.R

Defines functions plot_size save_plot plot.stim plot.stimlist

Documented in plot_size plot.stim plot.stimlist save_plot

#' Plot stimuli
#'
#' Plot stimuli in a stimlist. Returns a ggplot with attributes \code{width} and \code{height} that are the width and height of the image in pixels.
#'
#' @param x list of class stimlist
#' @param y omitted
#' @param ... Arguments to be passed to \code{\link{grid_stim}}
#'
#' @return ggplot
#' @export
#'
#' @examples
#' demo_stim("test") %>% plot()
#'
plot.stimlist <- function(x, y, ...) {
  grid <- grid_stim(x, ...)
  ggimg <- magick::image_ggplot(grid[[1]]$img)
  w <- grid[[1]]$width
  h <- grid[[1]]$height
  attr(ggimg, "width") <- w
  attr(ggimg, "height") <- h

  ggimg
}

#' Plot stim
#'
#' @param x stim
#' @param y omitted
#' @param ... Arguments to be passed to \code{\link{grid_stim}}
#'
#' @return ggplot
#' @export
#'
#' @examples
#' demo_stim("test")[[1]] %>% plot()

plot.stim <- function(x, y, ...) {
  stimlist <- validate_stimlist(x)
  plot(stimlist, ...)
}

#' Save plot
#'
#' The width and height are read from the plot if it was created from a stimlist, but can be overridden by setting width and height (in pixels). Se scale to change proportionally.
#'
#' @param plot Plot to save.
#' @param filename File name to create on disk. Include the extension.
#' @param ... Other arguments to pass to \code{ggplot2::ggsave}.
#'
#' @return NULL
#' @export
#'
#' @examples
#' \dontrun{
#'   p <- demo_stim("test") %>% plot()
#'   save_plot(p, "img.png")
#'   save_plot(p, "img.jpg", scale = 2)
#' }
save_plot <- function(plot = ggplot2::last_plot(), filename, ...) {
  dots <- list(...)

  width <- xget(dots, "width", "w") %||% attr(plot, "width") %||% NA
  height <- xget(dots, "height", "h") %||% attr(plot, "height") %||% NA
  dpi <- dots$dpi %||% 300
  w <- width/dpi
  h <- height/dpi

  ggplot2::ggsave(filename, plot, width = w, height = h,
                  units = "in", dpi = dpi, ...)
}

#' Get plot size
#'
#' This is most useful for setting image dimensions in Rmd code chunks. It will display text to copy for the code chunk only when running interactively.
#'
#' @param plot Plot to measure, defaults to last plot displayed.
#' @param dpi Plot resolution for determining size in inches (usually 300 for print and 72 for screen)
#'
#' @return invisibly returns a list of plot width and height in pixels
#' @export
#'
#' @examples
#' demo_stim() %>% plot()
#' plot_size() %>% str() # fig.width = 2.35, fig.height = 1.19
#' plot_size(dpi = 72) %>% str() # fig.width = 9.81, fig.height = 4.97
plot_size <- function(plot = ggplot2::last_plot(), dpi = webmorph_options("dpi")) {
  w <- attr(plot, "width")
  h <- attr(plot, "height")

  if (interactive()) {
    chunk <- sprintf("fig.width = %.2f, fig.height = %.2f\n",
            round(w/dpi, 2), round(h/dpi, 2))
    cat(chunk)
  }
  invisible(list(
    width = w[[1]],
    height = h[[1]]
  ))
}
facelab/webmorph documentation built on April 11, 2021, 6:34 a.m.