wilkelab / cowplot

cowplot: Streamlined Plot Theme and Plot Annotations for ggplot2
https://wilkelab.org/cowplot/
701 stars 84 forks source link

added dpi to set_null_device #160

Closed wsteenhu closed 4 years ago

wsteenhu commented 4 years ago

Given that I work on macOS, it took me some time to set up an environment where I can use custom fonts in ggplot2 that are non-standard. The workflow makes use of showtext and specifies cairo-devices in knitr::opts_chunk$set. I found that using this setup does not work without warnings in cowplot (complaining about the font that is not found), so my aim was to also set the null device of cowplot to cairo (which also fixed these warnings in other instances).

However, using cowplot::set_null_device("cairo") yields an error, stating that images cannot be created with other units than 'px' if dpi is not specified. A small change (adding the dpi = argument) fixed this error, enabling of setting the null device. Importantly, after this change my workflow with custom fonts worked again.

Could make this change to the source code?

PS: probably dpi can also be set to "auto" if preferred.

clauswilke commented 4 years ago

Note that you can work around the issue without changing the cowplot source code by defining your own null device:

my_null_device <- function(width, height) {
  if (requireNamespace("Cairo", quietly = TRUE)) {
    Cairo::Cairo(
      type = "raster",
      width = width, height = height,
      units = "in", dpi=300
    )
    grDevices::dev.control("enable")
  } else {
    warning("Package `Cairo` is required to use the Cairo null device. Substituting grDevices::pdf(NULL).", call. = FALSE)
    pdf_null_device(width, height)
  }
}

cowplot::set_null_device(my_null_device)