Search code examples
rplottime-seriesxtsquantmod

R Why plot.xts creates extra graph after calling lines?


Consider two following plots, first uses generic plot function and the second one uses plot.xts:

Generic plot

par(mfrow = c(2,1))
plot(1:5, type="l", main = "generic plot")
lines(5:1)

as expected, lines function adds to existing graph so it results in single graph

enter image description here

I've set mfrow = c(2,1) to show you that, there is only one graph. Now using xts data:

par(mfrow = c(2,1))
plot(xts(x = 1:5, order.by = 1:5+as.Date("2017-01-01")), type="l", main = "plot.xts")
lines(xts(x = 5:1, order.by = 1:5+as.Date("2017-01-01")), main = "plot.xts")

enter image description here

Unexpectedly it results in two graphs. Why?

My particular case is a bit more complex, but I've found this snippets of code the easiest way to reproduce my issue. Basically I want to keep adding xts data on one plot. I was able to accomplish that using generic plot and lines function.

Platform information: R version 3.4.3 (2017-11-30) Platform: x86_64-apple-darwin15.6.0 (64-bit) Running under: macOS High Sierra 10.13.2 quantmod_0.4-12 xts_0.10-1


Solution

  • The xts plotting functions don't really work like base plotting functions despite they fact the calls look the same.

    The plot.xts function returns an object. By default, if you don't assign the object anywhere, R will "print" the object which results in a plot being drawn. The lines.xts function changes the most recent plot object and adds a new series. Since the plot is not saved, that new object is printed as well. This new object remembers the first series as well as the newly added series.

    The best thing to do would be to save these object and only print them when you are done adding layers. For example

    par(mfrow = c(2,1))
    pp <- plot(xts(x = 1:5, order.by = 1:5+as.Date("2017-01-01")), type="l", main = "plot.xts")
    pp <- lines(xts(x = 5:1, order.by = 1:5+as.Date("2017-01-01")), main = "plot.xts")
    pp #plot will be drawn here