How to copy R ggplot to clipboard?

Viewed 2520

I cannot seem to make work the png(), bmp(), etc. with ggplot, and ggsave(filename="clipboard") does nothing. Any ideas?

3 Answers

Try this :

dev.new()
my_plot <- ggplot(data.frame(x=1:10,y=1:10),aes(x,y)) + geom_point()
my_plot
savePlot("clipboard")

Or if you don't want to display it at all (Windows) :

win.metafile()
my_plot2 <- ggplot(data.frame(x=1:5,y=1:5),aes(x,y)) + geom_point()
print(my_plot2)
dev.off()

Relevant: Save plot without showing it at all

I think the goal is just to put a plot into the clipboard. I wrote a function to do that by writing the plot to a temporary file. Since the OP is clearly on macOS, as am I, this function is for now only suitable for macOS. Adapt as needed.

plot_clipboard <- function(plot, width = 7, height = 6, device_fn = cairo_pdf) {

  # determine required file extension based on input for device_fn
  file_type <- deparse(substitute(device_fn))
  file_type <- gsub(".*(.{3})$", "\\1", file_type)
  tmpfile <- tempfile(fileext = paste0(".", file_type))

  # save plot to temp file
  device_fn(filename = tmpfile, width = width, height = height)
  print(plot)
  dev.off()

  message("Saved plot to temp file: ", tmpfile)

  # and copy this file into the clipboard
  sysname <- tolower(Sys.info()["sysname"])
  if (sysname == "darwin") {
    # macOS, make use of Applescript
    out <- system(command = paste0("osascript -e 'on run args' -e 'set the clipboard to POSIX file (first item of args)' -e end \"$@\"", tmpfile), intern = TRUE)
  # } else if (sysname == "windows") {
  #   # something for Windows here
  } else {
    message("Sorry, you're on your own!")
  }
}

It's still a bit work in progress. Pasting in Finder works fine, but pasting into a Word document doesn't (while Word correctly says it's about to paste a 'Files' object).

For writing scientific manuscripts, I'm still looking out for a function that writes a PDF file that's immediately paste-able into Word (so no quality loss), enabling me going from R to Word with only doing this:

analysis.1.2.3 <- my_research_data %>%
  ggplot() +
  geom_col() +
  younameit()

analysis.1.2.3 %>% plot_clipboard()

And then Cmd+V while in Word. As I said, work in progress :)

Related