Search code examples
rpdfgraphicsplotpng

Save a plot as PNG and PDF only by one call to the plot function in R


I would like to have a plot in both pdf and png formats:

pdf("test.pdf")
plot(sin, -pi, 2*pi)
dev.off()

png("test.png")
plot(sin, -pi, 2*pi)
dev.off()

But, I am searching for a trick (preferably, not by loading a new package) in which plot function only be called once:

#no plot in pdf!
pdf("test1.pdf"); png("test1.png")
plot(sin, -pi, 2*pi)
dev.off(); dev.off()

Any suggestion would be appreciated.


Solution

  • You can use dev.copy() for your purpose. For instance:

    pdf("test.pdf")
    a<-dev.cur()
    png("test.png")
    dev.control("enable")
    plot(sin, -pi, 2*pi)
    dev.copy(which=a)
    dev.off()
    dev.off()
    

    You take note of the pdf device through dev.cur and then copy the plot from the png device to the pdf one.