Question

Is there any way in R to create a png and a pdf simultaneously without having to run the same code twice? I'd like both a raster and vector version of some figures to be produced without having to do an external conversion and without rerunning the code if possible. dev.copy2pdf sounds like what I need, but it seems that it only works from interactive devices.

Here's an example of what I'm doing:

pdf("temp.pdf")
plot(1:10)
#more drawing here
dev.off()

png("temp.png")
plot(1:10)
#more drawing here
dev.off()

Which I'd like to shorten to:

start()
plot(1:10)
#more drawing here
saveToPDF()
saveToPNG()
Was it helpful?

Solution

There is an existing function dev.copy2pdf(), which does just what it says it will. There is also a function dev.print() which looks like it would make copying to a "*.png" file easy, but is in my experience pretty hinky.

The following two functions work well and have the added advantages of being uniformly named, and of taking all of their arguments in the same order as the familiar and related pdf() and png() functions:

saveToPDF <- function(...) {
    d = dev.copy(pdf,...)
    dev.off(d)
}

saveToPNG <- function(...) {
    d = dev.copy(png,...)
    dev.off(d)
}

## Try them out
plot(rnorm(99),  col="red")
saveToPDF("my.pdf", height=4,width=7)
saveToPNG("my.png", height=600, width=400)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top