Is there a way to specify portrait/landscape orientation per page using pdf()? - r

I am trying to find a way to set the rotation per page. For example, this is the trimmed down code I am using:
pdf('test.pdf',
paper='USr', width=90, height=12, onefile=TRUE)
grid.draw(grobtable1)
grid.draw(ggplot1)
grid.newpage()
grid.draw(grobtable2)
grid.draw(ggplot2)
grid.newpage()
grid.draw(table.portrait)
dev.off()
I would like all the pages except for the last one to be portrait. Is there any elegant way to do this using pdf()?
I have no experience with R Markdown yet, as I have read that might be a way to do what I desire. However, the code that I gave is something I use as a function, of which the plots and tables are being called from another function output. Hence, I thought using R Markdown would require me to make new Markdown files all the time.

I'm not sure if you can alter the pdf orientation in the middle of a run. You could write out to two files and merge them together using the staplr package. See here.

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.

Displaying png files from R into spotfire

I want to pass data from Spotfire to R and then display the plot constructed by R.
What is the best way to do this?
I’ve figured out the trick of putting images into Spotfire. It’s not hard if you follow these directions, but it’s done in a way very different from how you guess you would do it in Spotfire, and that’s why it took me awhile to figure out.
Here’s an overview of how to do it. You create a DocumentProperty which is a binary object, you write some Spotfire code that gives a value to that Document Property, and you display that binary object using a Spotfire Property Control of the “Label” type.
The confusing parts are that you DON’T use the Spotfire “Insert Image” tool at all, and that you DON’T use the filename generated inside the R code in Spotfire at all. Once you get used to the idea that the two most obvious ways you think you would approach the problem in Spotfire are entirely useless and wrong, you can make some progress.
I’ll leave out the spiderplot specifics because the code’s pretty long.
Here’s what you do.
1) Create a document Property in Spotfire of type “Binary”, e.g., “imageThatGoesBackToSpotfire”
2) You write some R code that generates an image and writes it to a file:
# get a temporary directory name on the local machine. You wouldn’t need to do this is you were just
# going to run it on your own, but you need to do it if you intend to let anybody else run it on their own machine.
tempfilebase = tempfile()
# take the tempfilebase and prepend it to a filename.
myFilename<-“someFileName.jpg”
myFullFilename <- paste(tempfilebase,myFilename,sep="")
#open a jpeg
jpeg(filename=myFullFileName)
# generate the image, however you normally would in R
plot(input)
# close the file
dev.off
# open a connection to that file.
myConnection<-file(myFullFileName,open=”rb”)
imageThatGoesBackToSpotfire<- data.frame(r=readBin(myConnection, what="raw", n=(file.info(myFullFileName)$size)))
close(myConnection)
3) Run your R script, above. Select some columns that are the “input” to the plot, and make the R script return outputs to the “imageThatGoesBackToSpotfire” DocumentProperties.
4) Create a text area in Spotfire.
5) Insert a Property Control into the text area of type “label”. (Click on the icon that’s circled in the picture below). This opens a dialog,
You need to register a data function with inputs and outputs, and the specific PNG data needs to be returned as a binary label.
Some details: http://spotfire.tibco.com/tips/2014/02/25/dynamically-displaying-images-in-a-text-area/

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

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.

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.

R: dev.copy2pdf, multiple graphic devices to a single file, how to append to file?

I have a script that makes barplots, and opens a new window when 6 barplots have been written to the screen and keeps opening new graphic devices whenever necessary.
Depending on the input, this leaves me with a potential large number of openened windows (graphic devices) which I would like to write to a single PDF file.
Considering my Perl background, I decided to iterate over the different graphics devices, printing them out one by one. I would like to keep appending to a single PDF file, but I do not know how to do this, or if this is even possible. I would like to avoid looping in R. :)
The code I use:
for (i in 1:length(dev.list())
{
dev.set(which = dev.list()[i]
dev.copy2pdf(device = quartz, file = "/Users/Tim/Desktop/R/Filename.pdf")
}
However, this is not working as it will overwrite the file each time. Now is there an append function in R, like there is in Perl. Which allows me to keep adding pages to the existing pdf file?
Or is there a way to contain the information in a graphic window to a object, and keep adding new graphic devices to this object and finally print the whole thing to a file?
Other possible solutions I thought about:
writing different pdf files, combining them after creation (perhaps even possible in R, with the right libraries installed?)
copying the information in all different windows to one big graphic device and then print this to a pdf file.
Quick comments:
use the onefile=TRUE argument which gets passed through to pdf(), see the help pages for dev.copypdf and pdf
as a general rule, you may find it easier to open the devices directly; again see help(pdf)
So in sum, add onefile=TRUE to you call and you should be fine but consider using pdf() directly.
To further elaborate on the possibility to append to a pdf. Although, multiples graphs can be put easaly into one file it turns out that it is impossiple or at least not simple to really append a pdf once finished by dev.off() - see here.
I generate many separate pages and then join them with something like system('pdfjam pages.pdf -o output.pdf' )*

Resources