我正在分析日常数据以查看价值何时会降低。我将每一天设置为分类变量,以便我可以区分每一天。但是我想让每一天都绘制在另一天的顶部而不是一个连续的图表,如下所示。
数据集:
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小时内看到值更低。谢谢提前。
方法尝试: 我尝试仅使用时间创建第3列,由于某些原因,以下代码无效:
time <- format(index(x), format = "%H:%M"))
data <- cbind(data, time)
答案 0 :(得分:3)
您需要一种总结当天每小时数据的方法。以下是您可能正在寻找的一些方法:
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()
答案 1 :(得分:2)
请尝试以下操作并让我知道它是否有效(这里我按照给定的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()