How to superimpose two ts objects with two different axes with ts.plot in R?

Viewed 41
library(tseries)
library(readxl)

data = read_excel(.......)

#Create tseries

equity = ts(data$EQUITY, start = c(2015,01,01), end = c(2020,01,01), frequency = 12)
cci = ts(data$CCI, start = c(2015,01,01), end = c(2020,01,01), frequency = 12)

#Plot the two series together

ts.plot(equity, cci, lty = c(1:2))

This code returns the following chart: R Chart.

Keeping in mind that I'd like to use the ts.plot function since I'm plotting other tseries objects and I'm not a fan of how ggplot2 handles them, is there a way to add a second axis to the chart and make it so that the two series appear superimposed instead of being far apart like in the linked image? The desired result would be like in this chart plotted with Python and matplotlib: Python Chart, possibly with a legend, too.

Any help would be greatly appreciated, thanks!

1 Answers

Use plot.ts rather than ts.plot like this. (See ?legend for other legend position keywords.)

z <- ts(cbind(1:10, 110:101))
col <- c("black", "blue")

plot(z[, 1], xlab = "", ylab = "", yaxt = "n", col = col[1])
axis(2, col.axis = col[1])
par(new = TRUE)
plot(z[, 2], xlab = "", ylab = "", yaxt = "n", col = col[2])
axis(4, col.axis = col[2])
legend("top", legend = c("z1", "z2"), lty = 1, 
  col = col, text.col = col)

screenshot

Related