Easy way to copy paste base graph from R Studio into word document - r

I need to copy paste R graphs into MS Word.
rando<-rnorm(1:100)
plot(rando)
when I copy the .png graph from R Studio into Word I get a negative space version of the graph:
Is there a cleaner/easier way to do this? I would be happy to use pdf or something else to present the graph.

As #Roland suggested:
Export -> Copy Plot to Clipboard (window with plot will pop-out) -> Metafile -> Copy Plot -> Paste to MSWord.
This seems a lot of clicks to me, rather as #user2633645 suggested save all plots as png then insert them in MSWord in one go.

?png
rando<-rnorm(1:100)
png(filename = "rando.png")
plot(rando)
dev.off()

You can use the devEMF package. It is repeatable, easy to use, and converts very nicely to pdf if needed.

(wow is this an old question, but I guess it's still an issue. I'm on RStudio v1.3.1073)
I came across 3 options:
Cross posting from https://github.com/rstudio/rstudio/issues/5103#issuecomment-679021780: "I've found two simple workarounds: Paste Special and choose TIFF, or (my preference) drag the image from the zoom window and drop in PowerPoint"
Snipping tool
You can specify the dimensions like in the RStudio plot export
windows(800,600) ## Opens graphic window. ctrl c/v works here.
plot(rando)

If you are doing this copy-plot-to-Word often or for several plots, consider creating an .Rmd file with your code, call knitr on that file, and use system("pandoc to convert your knitted .md file to Word.

Related

R program from Wikipedia doesn't plot

I want to use a R script which is publicly available from Wikipedia: https://commons.wikimedia.org/wiki/File:Correlation_examples2.svg .
This program is supposed to output an image but for some reason when I paste the code to Rstudio it doesn't plot.
What can I do to make it output the image?
Two main reasons:
The script by itself doesn't plot anything. It just sets up the function that will generate the image. So pasting the code by itself won't help and you need to call the 'output' function.
However the function by itself doesn't plot anything either. It saves the plot as Rplots.svg which contains the .svg code to plot the images.
To display the plot in RStudio, use for example the magick package.
output()
magick::image_read_svg('Rplots.svg')
Alternatively you can open the Rplots.svg file with a browser of your choice.

How to export mulitple PDFs from R

I'm fairly new to R and am running into some issues exporting multiple graphs from R into a PDF file. The graphs I've created are:
plot(mirt.nom.cohen.pf.fa2,type="info")
plot(mirt.nom.cohen.pf.fa2,type="infotrace")
plot(mirt.nom.cohen.pf.fa2,type="trace")
What would be the most efficient way to export these to a pdf?
Any guidance would be greatly appreciated.
Thank you!
Darko
Think of it this way - to save an R graph as a pdf file, you need to:
Open the pdf file;
Place the graph in that file;
Close the pdf file.
What this means in your case is that you have to do something like this:
pdf("plot1.pdf")
plot(mirt.nom.cohen.pf.fa2,type="info")
dev.off()
pdf("plot2.pdf")
plot(mirt.nom.cohen.pf.fa2,type="infotrace")
dev.off()
pdf("plot3.pdf")
plot(mirt.nom.cohen.pf.fa2,type="trace")
dev.off()
The 3 pdf files you created will be stored in R's working directory, which you can find with the command:
getwd()
Once you know where R saved the pdf files, you have to locate that directory on your computer and then you can manually select and open the files. Each file will be single-page and contain one graph.
As already suggested here, you can also create a single, multi-page pdf file which will contain all 3 graphs (one graph per page):
pdf("plot.pdf")
plot(mirt.nom.cohen.pf.fa2,type="info")
plot(mirt.nom.cohen.pf.fa2,type="infotrace")
plot(mirt.nom.cohen.pf.fa2,type="trace")
dev.off()
This file will also be stored in R's working directory.
If you look at the help of the pdf function in R, you'll discover that you can use it with various options (e.g., width and height):
help(pdf)
do you want one to a page, or all on the same page?
to simply get them to a pdf file, you open the pdf device, indicate the file name, and then everything until you close it will go there.
pdf("plots.pdf")
your statements
dev.off()

Unicode characters in plots to use in dynamic reports using R, Sweave and knitr

I have a problem properly displaying fonts in plots generated by ggplot2 in LaTeX reports generated by R studio in Sweave using knitr.
At first I was not able to properly generate pdfs with polish fonts but that problem was tackled in this post:
Unicode Characters in ggplot2 PDF Output
In short, the author adviced using Cairo package (in R) to generate plots using ggplot2.
This worked for me - once -> meaning I was able to generate a plot with polish characters, but when I am trying to use it in sweave document to generate LaTeX report using knitr like this:
<<pieniadze_graph,fig=TRUE,echo=FALSE>>=
library(Cairo)
cairo_pdf("TutorialExercisesPart2-pieniadze_graph.pdf")
plot1 <- qplot(expenditure, data = cas) + xlim(0, 8000) +
xlab(expression(paste("Pieniądze wydane na ucznia ($)"))) +
ylab("Liczba szkółńćźżś")
print(plot1)
#
I get an error.:
Running pdflatex on TutorialExercisesPart2.tex...failed
While investigating while that happend -> i found that the file that cairo is soppoused to generate is blank (there is a pdf file of a name given to cairo_pdf but it can not be opened with pdf viewer -> error cannot open text file)
Now one note is necessary: The cairo_pdf function requires file name to be set. So I give the pdf a name, that is required to be used later by the tex file in a format filename-chunk_name.pdf (So much for dynamic reports :P)
So I am not for the cairo_pdf option.
Is there a way to generate proper pdf files without cairo_pdf option?
I was not able to find anything more on this topic without the cairo-pdf...
When I delete the cairo part my tex file is generated nicely with an ugly looking dots labels PDF file in it...
Rather than opening a device like you do with calling cairo_pdf(), you should instruct knitr to use the device. Have a look at the knitr options and "dev" in particular. In summary, you need to
<<pieniadze_graph,fig=TRUE,echo=FALSE,dev='cairo_pdf'>>=
...
or to make it default for all chunks
opts_chunk$set(dev='cairo_pdf')
Ok I finally got it!
It really was a problem with Sweave coding in the chunk heading.
After #Matev's response I began testing the dev='cairo_pdf' -> but this did not change anything in the output.
Why? Because the
<<dev='cairo_pdf'>>=
#
is only interpreted by knitr Rnw file weaver!!! And I was using the Sweave weaver (this is set in the global options of R studio under Sweave section).
After recognising the not-so-obvious mistake (Because both Sweave and knitr use similar chunk heading script format) I seached what Leisch had to say about that in his Sweave Manual. This is his solution for everyone who has the same problem:
Put this code early in the document (after R libraries)
<<>>=
my.Swd <- function(name, width, height, ...)
grDevices::cairo_pdf(filename = paste(name, "pdf", sep = "."),
width = width, height = height)
#
You may now use the following code in seperate chunks
<<chunk_name,grdevice=my.Swd,fig=TRUE>>=
#
or as #Matev adviced globally set chunk options for the entire document (but again his answer was for the knitr weaver):
\SweaveOpts{grdevice=my.Swd}
Now You will get beautiful plots generated by the cairo_pdf device (base R device) which handles uniode fonts nicely!!! And they will get sweaved into Your dynamic reports like magic!
And I would like to thank Yihui for the knitr package which is GREAT!

How to save or copy in the clipboard a graph made with Statet/R/Eclipse?

My setup: Eclipse, R and Statet
I am using R from inside Eclipse using Statet.
I have made a graph (this is the plot of a time series, in case this is relevant information).
I now wish to save this graph as a JPG image (or BMP, or the like ...), or to copy this image in the clipboard. I need my graph in a PowerPoint presentation.
Does anyone know how to do that?
Thank you
jpeg('foo.png') more help is available by typing ?jpeg at the statet prompt. You may also be able to write to the clipboard, using a destination of clipboard instead of the filename, depending on your platform -- see ?connections for further details.

Redirecting R graphs to MS Word

I wonder how to redirect R graphs to MS Word? Like sink() redirect the R output to any file but not the graphs. I tried R2Wd but sometimes it doesn't work properly. Any comment and help will be highly appreciated. Thanks
To answer your direct question, the best way to get the results of R scripts and plots into word is probably via some form of Sweave. Look up odfweave to send R output to a LibreOffice file that can then be converted to word, or even opened directly in Word if you have the right plugin.
To create plots that can be editable (i.e you can alter the look of plots, move the legend etc) I would recommend saving the plot to an svg format (scalable vector graphic) that you can then edit using the excellent free vector graphics app inkscape.
For instance, if I create my ggplot2 graph as an object
library(ggplot2)
dataframe<-data.frame(fac=factor(c(1:4)),data1=rnorm(400,100,sd=15))
dataframe$data2<-dataframe$data1*c(0.25,0.5,0.75,1)
testplot<-qplot(x=fac, y=data2,data=dataframe, colour=fac, geom=c("boxplot", "jitter"))
You can use the Cairo package, which allows creation of svg files, I can then edit these in Inkscape.
library(Cairo)
Cairo(600,600,file="testplot.svg",type="svg",bg="transparent",pointsize=8, units="px",dpi=400)
testplot
dev.off()
Cairo(1200,1200,file="testplot12200.png",type="png",bg="transparent",pointsize=12, units="px",dpi=200)
testplot
dev.off()
For more info read this previous question that has more good answers Create Editable plots from R
Also, you can follow this advice from Hadley, and save the actual ggplot2 object, then load it later and modify it
save(testplot, file = "test-plot.rdata")
# Time passes and you start a new R session
load("test-plot.rdata")
testplot + opts(legend.position = "none")
testplot + geom_point()
To get sink() like behavior with MSword look at the wdTxtStart function in the TeachingDemos package. This uses R2wd internally, so you will see similar functionality, this just sends everything you do to the word document.
Graphs are not sent automatically since you may be adding to them, but once you know you are finished with the graph you can use wdtxtPlot to send the current graph to the word document.
If you know what you want to do ahead of time then sweave or something similar is probably the better approach (as has already been mentioned). The group that created Rexcel are also working on Sword that does sweave like things within MSword.

Resources