开发者

Using ggplot, how to have the x-axis of time series plots set up automatically?

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 b开发者_StackOverflow社区ase 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..


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.


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))


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


How about this one?


Code


set.seed(12345)
dat <- ts(data=runif(n=10, min=50, max=100), frequency = 4, start = c(1959, 2))
df <- data.frame(date=as.Date(time(dat)), Y=as.matrix(dat))
library(ggplot2)
ggplot(data=df, mapping=aes(x=date, y=Y))+geom_point()

Output


Using ggplot, how to have the x-axis of time series plots set up automatically?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜