Lars K. Lars K. - 2 months ago 16
R Question

xts plot in a loop: no output

The standard plot method immediately displays a result. But with xts objects, this only works when plot.xts is not called within a loop. For example, this code works correctly:

library(xts)
data(sample_matrix)
sample.xts <- as.xts(sample_matrix)
plot(sample.xts)


Whereas the following code does not display any result:

# dev.off()
par(mfrow=c(1,2))
for (i in seq(2)) {
plot(sample.xts)
}


Where is the plot in the second case?
And why xts.plot does not act like the standard plot function?

Answer

Plot returns a plot object, which in your first case gets printed by default. In a loop, or function, you need to explicitly print it.

par(mfrow=c(1,2))
for (i in seq(2)) {
    print(plot(sample.xts))
}