In this post you will learn how to properly paste an R plot\chart\image to a word file. There are few typical problems that occur when people try to do that. Below you can find a simple, clean and repeatable solution.
When you google how to paste a plot from R to a word file you find that there are some solutions. But they are not satisfactory. For example, stackoverflow highest-ranking reply offers to use the Rstudio button to export your plot as an Enhanced Metafile (EMF) format. Couple of things wrong with it: the first is that you need to start messing around with the device scaling, because the export remembers the port dimensions. The second is that the word file is often not the final version. For better readability\representation we often convert the word to a pdf format before sending\publishing. But then you get something funny which you may have seen before, and drove some people insane consumed much of some people’s time, myself included:
Without further ado, here is what you should do. Install the EMF R package(Philip Johnson). The package elegantly has the one function: emf
, which works the way you think it should:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# install.packages("devEMF") # if not installed already library(devEMF) tmp_file <- "EMF_plot.emf" # ?emf # if needed emf(file= tmp_file, pointsize= 10, width= 5, height= 3) # Opens a device temp_margins <- c(1.5, 2.3, 0.5, 0.2) # Adjust margins par(mfrow = c(1,1), mar = temp_margins, mgp=c(0.6, 0.3, 0), tcl = -0.15, las = 1) plot(rnorm(10), ylab="", xlab="") # create your plot grid(col= "grey") dev.off() # Close the device |
We are almost there.
The above code creates an EMF file (called EMF_plot.emf in this case) of your plot in the working directory. You can specify the width and height of the graphics region as you do for any other graphic devices; very handy when you need to produce similar charts in bulk. Now instead of playing around with the scaling inside Rstudio, I suggest to quickly move to word file and do the work there. This 24 seconds video shows how to do that:
The eventual PDF then looks as it should, not blurry as it does when pasting a PNG for example, and without those ugly diagonal grey lines you saw before. So suitable for corporate environment where often word format, rather than latex or markdown, is the starting point for collaboration.
Also succeeds as expected for an emf file pulled into LibreOffice on an Ubuntu box running 18.04 LTS. Thanks for the heads up on this package.