YQ.Wang YQ.Wang - 3 months ago 21
R Question

How to creat a time vector excluding the system date when using R?

I want to creat a time vector which starts at 0:05:00 A.M and ends at 0:00:00 A.M the next day.The interval between each time spot is 5 minutes;
Then I want a y-t line plot with qplot().

Here is my R code:

t<-strptime('0:05:00','%H:%M:%S')+(0:287)*300
y<-rnorm(288,5,1)
qplot(t,y,geom = 'line')


the outcome is like this:
outcom

As you can see, the 't' is added with system date 'Aug 05'.What I want is 'hour : minute' only.

What should I do with my code?

bVa bVa
Answer

Here is a solution using ggplot2 and POSIX formatting for dates which is easy to manipulate with ggplot:

df = data.frame(
t = seq(as.POSIXct("2016-01-01 05:00:00"), as.POSIXct("2016-01-02 00:00:00"), by = '5 min', tz = "Europe"), 
y = rnorm(229,5,1))

ggplot(df, aes(t, y)) + geom_line() + 
scale_x_datetime(labels = date_format('%H:%M', tz = "GMT"), breaks =  date_breaks('2 hours'))

enter image description here

Comments