Search code examples
rplotchartstime-seriesaxis-labels

Monthly time series plot with years on x-axis in R


I'd really appreciate any help to create a time series plot in R. I'm a total newbie and my programming knowledge is really limited. I just need to create this one graph and it has to be done in R, not Excel.

I have the following monthly data:

Time   HML
200207 6.28 
200208 3.44
200209 8.03
...
201412 1.47

I have a really hard time to understand how time variable is defined or how it should be converted.

Now I need to plot it so on the X-axis there are only years visible i.e. 2002, 2003, 2004, (...), 2014.

Here's my code:

plot(HML, type="l", lwd=2, col="red", ylab= "% return")
abline(h = 0, col = "black", lty = "solid")

Any help much appreciated.

Best regards, Martin


Solution

  • First, create a time series object! (using ts())

    Then plot, I guess R will show only years on X-axis automatically!

    #make Time to time series object
    a<-ts(rnorm(150),start=c(2002,7),freq=12);a
    plot(a, type="l", lwd=2, col="red", ylab= "% return",xlim=c(2002,2014),axes=F)
    axis(1,at=2002:2014,labels=2002:2014);axis(2);box()
    

    Explain code:

    1. start in ts() means the times of the first observation
    2. freq means the number of observations per unit of time.
    3. We can control the range of X-axis by xlim!
    4. I don't know how to show all years by code easily,but a stupid method I always use is create one by myself. Hence, adding axes=F in plot means do not show the default axis. Then, create what axis I hoped by axis() and label show all years!
    5. Finally, make a box around your picture! enter image description here

    BTW You can find more details by typing ?ts in R !