Using ggplot, how to automatically adjust the timeline axis graphs?

Is there a way to build one-dimensional time series of the "ts" class using ggplot, which automatically sets the time axis? I need something similar to plot.ts () of the base graphics.

It also seems to me that the roughest granularity of time is day. It is 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 will result in the observations being irregularly spaced horizontally, because the months / quarters are of unequal length. This may make more sense, but my audience is used to seeing months / quarters on a regular basis.

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

+3
source share
4 answers

ggplot2 does not support ts-objects: only the date and time dates of the POSIXct class class are supported. Therefore, you need to first convert the data to a suitable class.

See http://had.co.nz/ggplot2/scale_date.html for examples.

+4
source

My rude attempt at the POSIX generation function dates from the ts object, assuming the 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 should be able to lay out several time series. It would also be nice to be able to automatically align the points depending on the time of observation, so that we can do things like:

 qplot(presidents,lag(presidents)) 
+4
source

Example time series data? ts.

 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. In the above example, the start date is given, the monthly frequency is set and how long the date vector is created.

Hope this is useful in preparing data before using ggplot2 or anything else.

You can combine the above example with data.frame as follows:

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

This can be built in ggplot as follows:

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

All the best

Jay

+2
source

How about this?


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


enter image description here

0
source

Source: https://habr.com/ru/post/976643/


All Articles