Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save plot without showing it at all

Tags:

r

ggplot2

rstudio

Is it possible to save a plot without displaying it at all ?

I made a little ggplot hack to be able to copy graphs to powerpoint easily, it copies the plot to the clipboard, but one can see the device window open and close fast, it's a bit awkward, can I avoid this ?

I'm using windows and rstudio.

reproducible code:

library(ggplot)

`-.gg` <- function(e1,e2){
  assertthat::assert_that(is.numeric(e2),
                          length(e2)<= 2)
  if(identical(e2,0)) return(invisible(NULL))
  W <- 8
  H <- 4.5
  dev.new(width=W * head(e2,1), height=H * tail(e2,1),noRStudioGD =TRUE)
  print(e1)
  savePlot("clipboard", type="wmf")
  dev.off()
  e1
}

ggplot(data.frame(x=1:10,y=1:10),aes(x,y)) + geom_point() - 1 - 0

Edit:

My code, and chosen solution, have issues dealing with semi-transparency.It's ok most of the time, but exceptions will be annoying. Maybe a path to a general solution would be to save it with tempfile then read it into the clipboard, either through an appropriate R function, or with command line using system (maybe something that would open the file invisibly and copy).

like image 660
Moody_Mudskipper Avatar asked Nov 10 '17 11:11

Moody_Mudskipper


People also ask

How do you save a plot without showing it?

Simply call plt. close() at the end of each plot instead of plt. show() and they won't be displayed. This is the best solution as it doesn't change any global behaviour and requires just one line.

How do I save a figure without displaying in Python?

Avoid Display With ioff() Method We can turn the interactive mode off using matplotlib. pyplot. ioff() methods. This prevents figure from being displayed.

How do you save a plot graph?

Matplotlib plots can be saved as image files using the plt. savefig() function. The plt. savefig() function needs to be called right above the plt.


1 Answers

This works on Windows: use the win.metafile() device. If you give no filename, it saves to the clipboard. So your function should be

library(ggplot2)

`-.gg` <- function(e1,e2){
  assertthat::assert_that(is.numeric(e2),
                          length(e2)<= 2)
  if(identical(e2,0)) return(invisible(NULL))
  W <- 8
  H <- 4.5
  win.metafile(width=W * head(e2,1), height=H * tail(e2,1))
  print(e1)
  dev.off()
  e1
}

ggplot(data.frame(x=1:10,y=1:10),aes(x,y)) + geom_point() - 1 - 0
like image 103
user2554330 Avatar answered Oct 28 '22 18:10

user2554330