R loop through complete script, find all plots generated and save them - r

I have the following problem using R and not found a solution so far:
I have a script where I run several operation and generate some plots. At the end, I would like to have a nice piece of code that automatically saves all the plots generated into the current working directory. So far, I am using:
trellis.device(device="png", filename="Plot_A.png")
print(Plot_A)
dev.off()
Which is working fine for just one specific plot. Now I am looking for some kind of for loop that takes all the plots and saves them with the name of the plot as a png file

In grid based plotting packages (lattice and ggplot), you can store the plot in an object and call print on them to trigger actual rendering of the plot. What you could do is not render the image on the spot, but append any plots to a list. Then, at the end, you can loop over the plots and output them.
plot_list = list()
lattice_plot = xyplot()
plot_list = append(plot_list, lattice_plot)
for(plot in plot_list) {
png('name.png')
print(plot)
dev.off()
}

Not exactly an answer but an alternative workflow.
If you are saving your plots in order to use it somewhere else, for example to include them in a Word document or in a presentation, you could just put your code in an RMarkdown document and knitr it to generate an html or doc document with all the output generated by the code, including plots. With RStudio all that could be done with a few clicks.
It may even be easier to take all plots from the Word document than from a folder of png files.

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 using code to save plots in Rstudio?

Is there any way to save the plots by code in RStudio?
Like something in Python save.plt().
I have noticed the function savePlot can save the figures but I cannot load it in RStudio, since it reports the errors in loading X11().
This leads me to think about another question... What is your way to using R or what is the proper way to using R? As a beginner I found RStudio is super easy to use and I like the idea that saving all the environments into a single file. But apparently it is no need to using X11() in plotting...
If you want to save from code the plot that is displayed in the RStudio plot tab then you have to call for example
rstudioapi::savePlotAsImage("test.png",width=300,height=150)
Plots can be saved as a jpg:
jpeg("Name_of_your_plot.jpg")
# your plot for example
plot(x,y)
dev.off()
Instead of jpg you can choose other image formats such as png, pdf or PostScript. The above code can be modified as:
png("Name_of_your_plot.png")
# your plot for example
plot(x,y)
dev.off()
If you have a ggplot you can use ggsave.

How to plot many plots to a pdf and AND a subset to Rmarkdown report?

I need to generate about >50 plots. I want to save them all in one pdf and have just a few of them appear in my R markdown html output.
I can print many plots to a single pdf like this:
pdf("path/to/out.pdf")
for (sam in samples){
plot(sam) # simplified stand-in for many lines of code
}
dev.off()
That puts one sample's plot on each page of a pdf that I can flip through later.
I want some of those plots to appear in my markdown, without duplicating the plot code.
I've tried:
pdf("path/to/out.pdf")
count=0
for (sam in samples){
plot(sam) # simplified stand-in for many lines of code
if (sample(1:10,1)==1){ #randomly select a few examples
count = count + 1
dev.copy(which=dev.prev()) # to revert back to the default device
dev.set(dev.next()) # to resume printing to the same pdf
}
}
dev.off()
With this, the pdf is correct and count is >0, but the plots do not appear in the markdown report.
I think something from the dev.copy() family will do what I want but I can't seem to make it work. In other variants I tried, dev.print() complains about only printing from a screen device, or I get errors saying that I cannot copy to the same device, or cannot copy to a null device.
Similar questions (such as Saving plot as pdf and simultaneously display it in the window (x11)) often want to do the reverse: print to screen a then to a pdf. And they generally only deal with one plot.
I want to make several plots, and I want ALL of my plots to go to the pdf, but only a FEW to go to the Rmarkdown html report as an example of what is in the pdf.
I'm working on a mac using R 3.5.1, RStudio v1.1.456
Thanks in advance!

How to hide figures in knitr, but create them as png?

I am currently doing some statistical analysis in R and use knitr to generate results and an overview document.
There are some additional plots, which I want to be done and saved as a .png (with specified file name and location), but not included in the generated .html file (too many of them, and they are not at the end).
Using dev.copy(png, ...) works fine for generating the plots, but the figures appear in the .html. If I specify fig.keep=none the .png files are created, but blank.
Is there some way to do what I want?
This is from knitr website:
fig.show: ('asis'; character) how to show/arrange the plots; four
possible values are
asis: show plots exactly in places where they were
generated (as if the code were run in an R terminal)
hold: hold all
plots and output them in the very end of a code chunk
animate: wrap
all plots into an animation if there are mutiple plots in a chunk
hide: generate plot files but hide them in the output document
fig.show = 'hide' worked for me.

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