Slug Pue
Slug Pue

Reputation: 256

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()

Upvotes: 1

Views: 337

Answers (1)

Esben Eickhardt
Esben Eickhardt

Reputation: 3872

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()

Upvotes: 0

Related Questions