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

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' )*

Related

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

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.

How do I handle randomly selected graphics files in R exams for export to qti and moodle?

I have a spreadsheet of exam questions that I want to use to generate quizzes and exams using R exams, and I'd like to include graphics in some of the questions.
The template here (http://www.r-exams.org/templates/fruit/) begins by defining the images as long base 64 encoded strings as generated by
base64enc::base64encode("file.png")
This seems fine, but if I have a dozen or so images of which I might only want a question to use one, two, or three images selected at random for programmatically generated exercises, how can I avoid including the encoding for all dozen images with every single exercise?
The best I can think of at the moment is to include LaTeX syntax for graphics inclusion in a spreadsheet of possible question options, and as exercises are generated, use regular expressions to find the file names inside the \includegraphics{} commands that will be included, encode those as base 64 strings, and include them in the exercise file, but I'm wondering if there's a way I can do this without writing my own code to parse LaTeX.
First a few clarifications:
The fruit exercises include the images as Base64 strings because the three icons are quite small (12K per icon) and it is convenient to have all information within the Rnw/Rmd exercise without the need to store graphics files separately. It is just one trick that can be nifty and that we wanted to demonstrate.
For more and larger images one could do the same trick but it is probably less convenient. To illustrate how static images can be included in an exercise, the following template is available: http://www.R-exams.org/templates/Rlogo/ It uses the include_supplement() function to declare a certain file as a supplement for the exercises. If this is a graphic it can then be integrated into the exercises via \includegraphics{...} in Rnw exercises and via ![...](...) in Rmd exercises.
Each exercise just has to include the supplements it actually uses (and not all files from which these were sampled). And there is no need to do the Base64 encoding manually. This is done by the exams2xyz(...) functions automatically if needed.
Now for the scenario you describe. Say you have an exercise foo.Rmd in which you want to show one of three static images foo-1.png, foo-2.png, foo-3.png and ask questions about it. Then your R code might do something like:
i <- sample(1:3, 1)
img <- paste0("foo-", i, ".png")
include_supplement(img)
which randomly selects one of the three files and declares it to be an attachment. Then within the question text you would include the image via something like:
![](`r img`)
Caveats:
The code above assumes that the PNG images are located in the same directory as the Rmd exercise itself. If it is in a sub-directory bar/ say, you would need include_supplement(img, dir = "bar") etc.
If this exercise is rendered into HTML then the original file name (foo-1.png or foo-2.png or foo-3.png) would be visible in the HTML source code. This may (or may not) provide a hint for students what the correct answer is. If so, it would be better to include the file with a neutral name, e.g., include_supplement(img, target = "foo.png").
In Rnw exercises the code for including the graphic would be something like: \includegraphics{\Sexpr{img}}.

gnuplot - How can I save a graphics file of a plot that is the same as I designed it in xterminal?

I have been making plots for some time now, and they are precisely the way I like them, on screen. The data is coming in from sensors related to solar power collection and storage.
Plotted on screen they look great so I do a screen region capture to save them.
So now I would like to automate the saving process.
Here is what I have done so far:
I set up a cron job so they would be run right at midnight, capturing the whole day and saving it as a .png file
Then it moves the "today.dat" data file to the archive named by date.
This part is all working as designed.
EXCEPT, by using .PNG the images do not look the same.
I really thought png would be the best option, but it turns out that the font used for the X-axis (HH:MM ticks) is too thick and they run together. It looks like a crayon-drawn version of my plot designs.
Can someone please give me some guidance on how to best programatically generate the plots for saving so they look like the way I designed them?
As pointed out in the comments above, the best way is probably to use a different terminal for output to an image file, and simply ignore the fact that the generated images are not identical to what you see on your screen when using the x11 terminal. However, if you really need an exact copy, there are (at least) two options:
You could automate the process of taking a screenshot. You can even do this from within gnuplot, where it might come handy that the GPVAL_TERM_WINDOWID variable contains the X Windows ID for the current plot window. You can use that to make a screenshot of the window after you made the plot:
system(sprintf("xwd -id 0x%x | convert xwd:- screenshot.png", GPVAL_TERM_WINDOWID))
Here I included a call to convert to convert the xwd file format to png.
Another option is to use the xlib terminal, which saves the sequence of commands that the gnuplot_x11 helper application turns into the window you see on the screen. For example,
set term push; set term xlib; set output "file.xlib"; replot; set output; set term pop
will create the file file.xlib that has all the information of the last plot. To later view this plot, use
gnuplot_x11 -noevents -persist < file.xlib
where you might have to specify the path to gnuplot_x11.
Similar as #user8153 suggested for x11, you can use import, which is as convert an imagemagick tool
system("import -window ".GPVAL_TERM_WINDOWID." screenshot.png")
Convenient is also a shortcut to copy the image into clipboard and paste it with Ctrl+v elsewhere:
bind Ctrl-c 'system("import -window ".GPVAL_TERM_WINDOWID." png:- | xclip -sel clip -t image/png")'
See also Show graph on display and save it to file simultaneously in gnuplot.

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/

Generate PDF with vector graphics

I have an idea where I need to be able to dynamically create a PDF-file thats supposed to contain a number of vector-graphical images.. I also need to be able to "absolute" position the vector images within the PDF.. I then later on need to be able to download the generated PDF-file.. is this possible?..has anyone done something like this before?.. as far as I can remember there is a pretty good support for doing this using none vectorized-images (jpg,png etc).. but is it possible to use eps-files and other vector images?
You can use pdflatex to generate the pdf.
(pdf)Latex has really good support for importing svg and eps.
When you use Inkscape you can chose to export to tex/latex and it generates code for you.

Resources