Search code examples
raxis-labels

Matplot R manually labelling x-axis


I have a problem labelling my matplot x-axis row. So I have 1388 instances, but I want my X-axis to a custom labeling in the form of a sequence in dates. My R code looks like this:

Dates <- seq(as.Date("2004/01/29"), as.Date("2009/07/31"), by = "quarter")

matplot(seq(1388), t(Alldata[1, ]), type = "l", 
    lwd = 1, lty = 1, col = 1:10, xlab = "Dates", ylab = "Strike", 
    main = paste("TEST"), xaxt='n')
axis(side = 1:23, at=1, labels = paste(Dates, 1:23))

Can anybody help me get the Dates into the x-axis? I have tried using same method as this: Change axis labels with matplot in R but it doesn't work. AllData is from an excel file in which the first number of rows looks like this: enter image description here


Solution

  • I think you have confused the way the function axis works. In answering below I will generate a random matrix to replace your Alldata which I don't have access to

    Alldata <- t(as.matrix(rnorm(23)))
    

    We can generate the plot again:

    matplot(seq(23),  Alldata[1, ], type = "l", 
            lwd = 1, lty = 1, col = 1:10, xlab = "Dates", 
            ylab = "Strike", main = paste("TEST"), xaxt='n')
    

    Now, its import to know what the arguments to axis are. First side this is literally the side of the the rectangle on which the plot is drawn. It is one of the numbers 1, 2, 3, 4 corresponding to bottom, left, top, right, respectively.

    You want the axis to be on the bottom so we set this to 1.

    Next, the at argument, is for where the tick marks should be drawn. So if you have 10 points on your line, and you set this value to 1:10 it will draw a tick mark at each point on the axis. If you set it to c(2,4,6,8,10) it will draw a mark at every second point on the axis. In your case you've set it to 1, which would draw only one tick. Although since the side was set to 1:23 none showed up.

    labels This argument will label the ticks which are drawn. Ideally it should be a vector the same length as the at value. You can make sure that they are the same length by creating an index variable and using this as the at variable and to index the labels.

    This gets us to:

    index <- c(1,7,14,21)
    axis(side = 1, at = index, labels = paste(Dates, 1:23)[index])
    

    I think having a full range of dates would look cluttered. But you can drop the index and choose the below if you prefer:

    axis(side = 1, at = 1:23, labels = paste(Dates, 1:23))