Copy R plot to clipboard with custom size

2019-03-24 15:23发布

问题:

Is there a way to get R / RStudio to copy a plot to the clipboard with a custom size?

RStudio has this function, but you have to define the size everytime and there is some extra clicking which I am sure is avoidable.

I tried my best with saving as jpeg or else with file="clipboard" and then - after plotting - dev.off(). No error messages, but also nothing in the clipboard.

Here is an example:

data(mtcars)
jpeg(file = "clipboard",width = 800, height = 600, units = "px", pointsize = 12,
     quality = 100,
     bg = "white", res = NA, family = "", restoreConsole = T)
hist(mtcars$mpg)
dev.off()

Any ideas on how this can be achieved?

回答1:

The best way would be to be able to control the size in Rstudio, but as you have found out yourself from the Rstudio-website, Rstudio doesn't support that. The following code saves your plot to wmf. There is also a workaround to a save to bitmap, which involves some clicking, but at least you don't have to specify the size any more:

data(mtcars)
windows(800, 600, pointsize = 12) #opens a separate window with the size you want 
hist(mtcars$mpg) #draw to this (active) window
savePlot("clipboard", type="wmf") #saves plot to WMF

Unfortunately, it seems to be impossible to save to jpg format to the clipboard. You can copy it to a bitmap by going to this window, click CTRL-C and the graph is on the clipboard as bitmap with 800:600.

EDIT: The windows command only works on Windows.
For Mac, it should be replaced by: quartz(width=8,height=6,pointsize=12,dpi=100) (width/height in inches!)

For linux try x11(width=8,height=6,pointsize=12,dpi=100) (untested).



回答2:

With Windows and RStudio, you click Export, click Copy Plot to Clipboard, and Copy Plot.

Then, paste into Word or PowerPoint or whatever.

No need to change sizes unless you want to.

This is not command line, but hardly seems onerous.