rplotplotrix

twoord.plot axis changing


I am using twoord.plot for the first time, and I am having trouble getting the x axis set to years for a time-series data set. I have two different y-axes on different scales. Here is the code that I am working with.

#Install BatchGetSymbols
install.packages('BatchGetSymbols')
library(BatchGetSymbols)

#Get data from FRED
library(quantmod)
getSymbols('CPALTT01USM661S', src = 'FRED')

library(quantmod)
getSymbols('M2SL', src = 'FRED')

#Create data sets with equal number of observations

CPI = CPALTT01USM661S["1960-01-01/2019-01-01"]
M2 = M2SL["1960-01-01/2019-01-01"]

library(plotrix)
twoord.plot(rx = time(CPI), ry = CPI, lx = time(CPI), ly = M2, 
            main = "Money Supply and Prices",
            xlim = NULL, lylim = NULL, rylim = NULL,
            mar = c(5,4,4,4), lcol = "red", rcol = "blue", xlab = "", lytickpos = NA,
            ylab = "M2", ylab.at = NA,
            rytickpos = NA, rylab = "CPI", rylab.at = NA, lpch = 1,rpch = 2,
            type = "l", xtickpos = NULL, xticklab = NULL, 
            halfwidth = 0.4, axislab.cex = 1, do.first = NULL)

Here is the graph that I am getting. Notice the x-axis is not in years.

enter image description here


Solution

  • The date values ( beginnings of each month) are in the index of the matrices, so to extract the year beginnings get every 12th item:

    twoord.plot(rx=time(CPI), ry=CPI, lx=time(CPI),ly = M2, main="Money Supply and Prices",xlim=NULL,lylim=NULL,rylim=NULL,
                mar=c(5,4,4,4),lcol="red",rcol="blue",xlab="",lytickpos=NA,ylab="M2",ylab.at=NA,
                rytickpos=NA,rylab="CPI",rylab.at=NA,lpch=1,rpch=2,
                type="l",
                xtickpos=index(CPI)[seq(1,nrow(CPI), by=12)], #tick at year start
                xticklab=format( index(CPI)[seq(1,nrow(CPI), by=12)], "%Y"), #just year
                halfwidth=0.4, axislab.cex=1,
                do.first=NULL, las=2)   # not sure why las=2 didn't seem to work.
    

    enter image description here