R - 仅从 xts、zoo 和 POSIXct 中提取时间

R - extracting time only from xts, zoo and POSIXct

我正在分析日常数据以查看该值何时会更低。我将每一天设置为分类变量,这样我就可以区分每一天。但我想把每一天都绘制在另一天之上,而不是如下所示的连续图表。

数据集:

                    Value        Day
2013-01-03 01:55:00 0.35435715    1
2013-01-03 02:00:00 0.33018654    1
2013-01-03 02:05:00 0.38976118    1
2013-01-04 02:10:00 0.45583868    2
2013-01-04 02:15:00 0.29290860    2

我目前的ggplot代码如下:

g <- ggplot(data = Data, aes(x = Index, color = Dates)) +
    geom_line(y = Data$Value) +
    scale_x_datetime(date_breaks = TimeIntervalForGraph, date_labels = "%H") +
    xlab("Time") +
    ylab("Random value")

如果有人能指导我如何将 x 轴转换为 24 小时时间序列,以便我可以在同一图表上绘制每一天,以查看 24 小时内值何时较低,我将不胜感激 hrs.Thanks提前。

尝试过的方法: 我尝试只用时间创建第 3 列,由于某些原因,以下代码不起作用:

time <- format(index(x), format = "%H:%M"))
data <- cbind(data, time)

请尝试以下操作,如果有效请告诉我(这里我使用给定的 tm 时间列):

Data$tm = strftime(Data$tm, format="%H:%M:%S")

library(ggplot2)
ggplot(Data, aes(x = tm, y = Value, group = Day, colour = Day)) +
  geom_line() +
  theme_classic()

您需要一种方法来汇总一天中每个小时的数据。以下是您可能正在寻找的一些方法:

library(xts)
library(data.table)
library(ggplot2)

tm <- seq(as.POSIXct("2017-08-08 17:30:00"), by = "5 mins", length.out = 10000)
z <- xts(runif(10000), tm, dimnames = list(NULL, "vals"))

DT <- data.table(time = index(z), coredata(z))
# note the data.table syntax is different:
DT[, hr := hour(time)]

# Plot the average value by hour:
datByHour <- DT[, list(avgval = mean(vals)), by = c("hr")]

# Use line plot if you have one point per hour:
g <- ggplot(data = datByHour, aes(x = hr, y = avgval, colour = avgval)) +
    geom_line()


datByHour <- DT[, list(avgval = mean(vals)), by = c("hr")]
# visualise the distribution by hour:
g2 <- ggplot(data = DT, aes(x = hr, y = vals, group = hr)) +
    geom_boxplot()