'How to plot two series in one single plot with different y-axis in plot.xts in R (current version of xts)

I'm trying to recreate this plot that I made with the old (pre 0.10-0) version of xts. Here's some example data:

library(xts)  # Run using xts_0.9-7

set.seed(190)
modelo_1 <- arima.sim(n = 252*8,list(ar = c(.99999),sd = sqrt(0.5)))
set.seed(256)
modelo_2 <- arima.sim(n = 252*8,list(ar = c(.9999),sd = sqrt(0.75)))

d1 <- as.Date("2008-01-01")
series_1 <- xts(modelo_1, seq(d1, by = "days", along.with = modelo_1))
series_2 <- xts(modelo_2, seq(d1, by = "days", along.with = modelo_2))

The code below uses the old version to create the graph I want.

par(mar = c(5, 4, 4, 4))
plot(series_1, las = 1, main = "", mar = c(5, 2, 2, 5))
par(new = TRUE)
plot(series_2, col = 2, axes = FALSE, main = "Two Series")
axis(4, las = 1)
lnames <- c("Series 1 (left)", "Series 2 (right)")
legend("top", legend = lnames, lty = 1, cex = 0.85, col = c(1, 2), bty = "n")

enter image description here

How can I create this plot with the new version of plot.xts()? Here's what I've tried, but both series use the same axis.

plot(cbind(series_1, series_2))
lnames <- c("Series 1", "Series 2")
addLegend("bottom", legend.names = lnames, ncol = 2, lty = 1, lwd = 1, cex = 1)

The old way of doing this is not working anymore, because of this issue.

plot(series_1, las = 1, yaxis.right = FALSE,yaxis.same = FALSE)
par(new = TRUE)
plot(series_2, col = 2, bty = "n", xaxt = "n", yaxt = "n", xlab = "", ylab = "")
axis(4, las = 1)
lnames <- c("Series 1", "Series 2")
legend("topleft", legend = lnames, col = 1:2, lty = 1, cex = 0.85)


Solution 1:[1]

I don't speak English very well so forgive me. Below is the code with the change so that it plots as it was before. note that the only change was to put the index as x in the plot function. Same index for both plot() functions

library(xts)  # Run using xts_0.9-7

set.seed(190)
modelo_1 <- arima.sim(n = 252*8,list(ar = c(.99999),sd = sqrt(0.5)))
set.seed(256)
modelo_2 <- arima.sim(n = 252*8,list(ar = c(.9999),sd = sqrt(0.75)))

d1 <- as.Date("2008-01-01")
series_1 <- xts(modelo_1, seq(d1, by = "days", along.with = modelo_1))
series_2 <- xts(modelo_2, seq(d1, by = "days", along.with = modelo_2))
#O código abaixo usa a versão antiga para criar o gráfico que eu quero.

 plot.new()
par(mar = c(5, 4, 4, 4))
plot(index(series_1),series_1, las = 1, main = "", 
     type = 'l', mar = c(5, 2, 2, 5))
par(new = TRUE)
plot(index(series_1),series_2, col = 2, axes = FALSE,
     type = 'l', main = "Two Series")
axis(4, las = 1)
lnames <- c("Series 1 (left)", "Series 2 (right)")
legend("top", legend = lnames, lty = 1, cex = 0.85, col = c(1, 2), bty = "n")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ronaldo Lamp