3

I have a function that both returns some statistics and makes a plot using R base graphics. I want to suppress the plotting from that function and instead return the plot as an object, so that plotting or not can be controlled from outside the function.

I've tried:

Using the gridGraphics package I can convert a base graphics plot to an object as suggested in this question:

plot(1:10)
grid.echo()
a = grid.grab()
grid.draw(a)

The remaining problem is that plot() command draws the plot that I want to suppress. Thus I tried to suppress it by plotting to a device in a temp file like answer here suggests. Code becomes:

ff = tempfile()
svg(filename = ff)
plot(1:10)
grid.echo()
a = grid.grab()
dev.off()
unlink(ff)

but now, grid.echo() can not find any graphics to echo, and throws warning:

Warning message:
In grid.echo.recordedplot(recordPlot(), newpage, prefix, device) :
  No graphics to replay

I've traced this problem back to grid.echo() not being able to echo graphics from other devices than the Rstudio default device, regardless of being in a temp file or not. This is in itself strange, since grid.echo() docs says it echoes graphics from the current device, not mentioning any restrictions.

Can anyone help me to solve the problem of suppressing base graphics plot and returning it as object, either by suggesting how to fix my broken attempt, or with another approach?

Anton
  • 365
  • 2
  • 12

1 Answers1

0

LocoGris solved the problem in this related question about the behaviour of grid.echo.

The following code will plot the unwanted graphics output into a tempfile, save the plot as a grid object using grid.echo and grid.grab before unlinking the tempfile so that only the plot object remains, thereby producing the besired behaviour:

ff = tempfile()
svg(filename = ff)
plotfun <- function() plot(1:10)
grid.echo(plotfun)
a = grid.grab()
dev.off()
unlink(ff)

The difference to code in question is that the plotting in R base graphics is put into a function and passed to grid.echo, instead of relying on grid.echo to automatically find what it needs from the current device.

Potentially useful note: grid.echo will plot two times, which can be seen if using regular svg() without tempfiles, as two files will appear with the same plot. I assume that the first plot is in R base graphics and the second one is the echo using the grid system.

Anton
  • 365
  • 2
  • 12