Search code examples
rplotxts

Plotting in R: How to generate a pdf using plot.xts inside a function


So here is my problem: if I run the following in the global environment, everything works as expected:

pdf("~/test.pdf")
plot.xts(xts(x = runif(10), order.by = Sys.Date() + 0:9))
dev.off()

However, I would like to output xts plots to pdf via functions, i.e. doing

plot_test <- function(){
    pdf("~/test.pdf")
    plot.xts(xts(x = runif(10), order.by = Sys.Date() + 0:9))
    dev.off()
}
plot_test()

My problem is that when I do this, the resulting pdf is empty. This problem seems to be specific to plot.xts because the built-in plotting functions of R do work when implemented in this way.

I have tried fiddling around with dev.set, dev.new etc, but cannot figure out what the issue is. I'm assuming it has something to do with plot.xts not writing to the device initiated by pdf()


Solution

  • Your have to use "print" when you are inside a function.

    plot_test <- function(){
        pdf("~/test.pdf")
        print(plot.xts(xts(x = runif(10), order.by = Sys.Date() + 0:9)))
        dev.off()
    }
    plot_test()