Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

time series plot with x axis in "year"-"month" in R

Tags:

r

I have a "monthly data" I want to plot the data such that I get a date in the format %Y-%m" (2001-01) on the x-axis. Say my data is pcp <- rnorm(24).

I have tried:

PCP <- ts(pcp, frequency = 12, start = 2001)
plot(PCP) 

but the plot only has years on the x-axis.

How do I get a plot with the date format I desire on the x-axis?

like image 953
mms Avatar asked Jul 20 '13 02:07

mms


2 Answers

Here's an idea with toy data since the question is not reproducible. Hopefully it helps

R> foo = ts(rnorm(36), frequency = 12, start = 2001)
R> plot(foo, xaxt = "n")
R> tsp = attributes(foo)$tsp
R> dates = seq(as.Date("2001-01-01"), by = "month", along = foo)
R> axis(1, at = seq(tsp[1], tsp[2], along = foo), labels = format(dates, "%Y-%m"))

Output

ggplot version with data that looks like yours

R> df = data.frame(date = seq(as.POSIXct("2001-01-01"), by = "month", length.out = 36), pcp = rnorm(36))
R> library(ggplot2)
R> library(scales)
R> p = ggplot(data = df, aes(x = date, y = pcp)) + geom_line()
R> p + scale_x_datetime(labels = date_format("%Y-%m"), breaks = date_breaks("months")) + theme(axis.text.x = element_text(angle = 45))

enter image description here

like image 179
Jake Burkhead Avatar answered Nov 07 '22 05:11

Jake Burkhead


I find that the excellent xts package is the best way to store your data. If you've not got it, you can download with install.packages('xts').

Let's start from basics -- including making pcp, as you've not supplied it.

require(xts)
pcp <- rnorm(24)
PCP <- ts(pcp, frequency = 12, start = 2001)
plot(as.xts(PCP), major.format = "%Y-%m")

This gives you a chart something like the following. You can tweak the dates by altering the string passed to major.format. For example, "%b-%y" yields dates in the Jan-01 format for Jan 2001.

example plot

like image 12
ricardo Avatar answered Nov 07 '22 06:11

ricardo