tags:

views:

543

answers:

3

Is there a way of plotting a univariate time series of class "ts" using ggplot that sets up the time axis automatically? I want something similar to plot.ts() of base graphics.

Also it seems to me that the coarsest time granularity is a day. Is that right? In my work I have to work with monthly and quarterly data and assigning each observation to the beginning/end of the month/quarter would cause the observations to be irregularly spaced horizontally since months/quarters are of unequal length. That may make more sense, but my audience is used to seeing months/quarters regularly spaced.

I know I can solve all of the above by manually setting up the x-axis as a time axis or as a numeric axis with my own labels. I am specifically looking for a method that does this automatically by using the time information in the ts object..

+3  A: 

ggplot2 doesn't support ts-objects: only dates of class date and times of class POSIXct are supported. So you would need to convert your data first to a suitable class.

Have a look at http://had.co.nz/ggplot2/scale_date.html for examples.

learnr
+3  A: 

My crude attempt at a function to generate POSIX dates from a ts object, assuming that periods are years:

tsdates <- function(ts){
  dur<-12%/%frequency(ts)
  years<-trunc(time(ts))
  months<-(cycle(ts)-1)*dur+1
  yr.mn<-as.data.frame(cbind(years,months))
  dt<-apply(yr.mn,1,function(r){paste(r[1],r[2],'01',sep='/')})
  as.POSIXct(dt,tz='UTC')
}

This can be used with ggplot as:

qplot(tsdates(presidents),presidents,geom='line')

A more complete solution would need to be able to lay out multiple time series. Also it would be nice to be able to automatically align points according to the time of observation so that we can do things like:

qplot(presidents,lag(presidents))
Jyotirmoy Bhattacharya
A: 

Hi,

Time series data from the ?ts example.

gnp <- ts(cumsum(1 + round(rnorm(100), 2)), start = c(1954, 7), frequency = 12)

new.date <- seq(as.Date(paste(c(start(gnp),1), collapse = "/")), by = "month", length.out = length(gnp))

The seq function can work with date objects. The example above provides the starting date, specifies a monthly frequency and signifies how long of a date vector to create.

Hopefully this is helpfully in your data preparation before using ggplot2 or something else.

You can combine the example above into a data.frame like this:

dat <- data.frame(date=new.date, value=gnp) 

This can be plotted in ggplot like this:

ggplot(data=dat) + geom_line(aes(date, gnp))

All the best,

Jay

Jay
To create a dataframe for ggplot you could do something like this:dat <- data.frame(date=seq(as.Date(paste(c(start(gnp),1), collapse = "/")), by = "month", length.out = length(gnp)),value=gnp)
Jay