Question

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?

Était-ce utile?

La solution

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).

Autres conseils

I know this is an old post, but recently looking to do the same I came across this Gist which worked well:

https://gist.github.com/dpashouwer/4223903d3ed5783158b7e63992155649

library(tidyverse)

gg_to_clipboard <- function(plot = last_plot(), width = 1000, height = 600, pointsize = 40){
    win.graph(width = width, height = height, pointsize = pointsize)
    plot %>% print()
    savePlot("clipboard", type = "wmf")
    dev.off()
}

ggplot(data = mtcars, aes(x = mpg)) + geom_histogram()

gg_to_clipboard()

Making the function makes it very simple.

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top