Search code examples
raxis-labels

Change axis labels with matplot in R


I'm trying to change the x axis in a matplot, but this command doesn't work:

TimePoints=1997:2011
matplot(t(DataMatrix),type='l',col="black",lwd=1,xlab="Anni",ylab="Rifiuti",main="Produzione rifiuti")
axis(side=1,at=TimePoints,labels=TimePoints)

with plot I used this without problems. How can I fix it? Here you can find the objects: https://dl.dropboxusercontent.com/u/47720440/SOF.RData


Solution

  • I usually do this as follows:

    1. Omit the axes altogether.
    2. Add the axes with desired options one by one.

    In R:

    # Add argument axes=F to omit the axes
    matplot(t(DataMatrix),type='l',col="black",lwd=1,xlab="Anni",ylab="Rifiuti",main="Produzione rifiuti",axes=F)
    
    # Add Y-axis as is
    axis(2)
    
    # Add X-axis
    # Note that your X-axis range is not in years but in the "column numbers",
    # i.e. the X-axis range runs from 1 to 15 (the number of columns in your matrix)
    # Possibly that's why your original code example did not work as expected?
    axis(side=1,at=1:ncol(DataMatrix),labels=TimePoints)