swolf
swolf

Reputation: 1143

Scaling of plot in ggsave() different when RStudio plot pane is active

I cannot provide a reproducible example for this, but I wanted to ask about a curious behavior of the ggsave() function: I am experiencing the following:

  1. I create a ggplot, by assigning a plot to a variable, let's say p
  2. I evaluate p and - as it should be - the plot is displayed in the plot pane of RStudio.
  3. My next call is ggsave(plot = p, filename = "plot.pdf"), the plot is written to plot.pdf and R gives me the dimensions of the written plot on the console.

The strange thing is: When the RStudio plot pane is active (i.e. a RStudio graphics device is open), the dimensions of the plot written by ggsave() in step 3 are different than when no RStudio graphics device is open. Consequently, the scalings of the written plot are off. In other words: Step 3 produces different results depending on the execution of step 2. Does anyone know why this is the case? I thought that ggsave() is totally independent of any RStudio device. Or does this only happen on my machine?

This is my sessionInfo():

R version 3.4.1 (2017-06-30)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Sierra 10.12.6

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

locale:
[1] de_DE.UTF-8/de_DE.UTF-8/de_DE.UTF-8/C/de_DE.UTF-8/de_DE.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] ggplot2_2.2.1     scales_0.4.1      data.table_1.10.4

loaded via a namespace (and not attached):
 [1] ggrepel_0.6.12     Rcpp_0.12.12       digest_0.6.12      grid_3.4.1         plyr_1.8.4         gtable_0.2.0       rlang_0.1.2        lazyeval_0.2.0    
 [9] labeling_0.3       RColorBrewer_1.1-2 tools_3.4.1        munsell_0.4.3      compiler_3.4.1     colorspace_1.3-2   sciplot_1.1-1      tibble_1.3.3

Upvotes: 3

Views: 1126

Answers (1)

Z.Lin
Z.Lin

Reputation: 29125

Expanding on Andrey Kolyadin's comment above...

From ggsave() documentation 'width, height Plot size in units ("in", "cm", or "mm"). If not supplied, uses the size of current graphics device.'

If we dig into the code behind ggsave, there's a snippet that says:

if (any(is.na(dim))) {
  if (length(grDevices::dev.list()) == 0) {
    default_dim <- c(7, 7)
  }
  else {
    default_dim <- grDevices::dev.size() * scale
  }
...

Which means that if the dimensions are not specified by the user:

  1. if there's no active graphics device at all, default dimensions are 7 x 7;

  2. if there's at least one active graphics device, use the dimensions of the last one (multiplied by scale, which defaults to 1).

RStudio's plot pane is a graphics device. So ggsave's behaviour differs depending on whether there's anything there.

Upvotes: 4

Related Questions