keep only hour: minute:second from a “POSIXlt” “POSIXt” object

前端 未结 1 1606
星月不相逢
星月不相逢 2021-01-01 04:03

I am making a plot in R (plotting three days of a time series in a single plot). I have a \"POSIXlt\" \"POSIXt\" vector and I need to keep only the time (hour,minutes...) wi

相关标签:
1条回答
  • 2021-01-01 04:41

    Suppose we have POSIXct values x.

    library(chron)
    
    # input
    y <- 1:5
    x <- as.POSIXct(c("2004-09-08 13:50:00", "2004-09-08 14:00:00", "2004-09-08 14:10:00",
    "2004-09-08 14:20:00", "2004-09-08 14:30:00"))
    

    1) Convert them to chron class "times" and plot:

    ti <- times(format(x, "%H:%M:%S"))
    plot(y ~ ti)
    

    2) or you could do this with zoo:

    library(zoo)
    
    z <- zoo(y, x)
    
    # convert index to "times" class and plot
    zz <- z
    time(zz) <- times(format(time(zz), "%H:%M:%S"))
    plot(zz)
    

    2a) or use ggplot2 with autoplot.zoo to plot:

    library(ggplot2)
    autoplot(zz) + scale_x_chron(format = "%H:%M")
    

    2b) We could also handle this solely through labelling rather than converting the index class. This uses zoo/ggplot2/scales but not chron times and simply relabels the X axis:

    library(scales)
    autoplot(z) + scale_x_datetime(breaks = "10 min", labels = date_format("%H:%M"))
    
    0 讨论(0)
提交回复
热议问题