在xaxis和yaxis中绘制时间序列数据

时间:2013-01-18 20:11:54

标签: r ggplot2 time-series

x <- structure(list(Date = structure(c(15358, 15359, 15362, 15363, 
15364, 15365), class = "Date"), EndTime = structure(c(1327016747, 
1327166720, 1327361839, 1327446733, 1327533097, 1327619504), class = c("POSIXct", 
"POSIXt"), tzone = ""), ThresholdTime = structure(list(sec = c(0, 
0, 0, 0, 0, 0), min = c(0L, 0L, 0L, 0L, 0L, 0L), hour = c(9L, 
9L, 9L, 9L, 9L, 9L), mday = c(20L, 21L, 24L, 25L, 26L, 27L), 
    mon = c(0L, 0L, 0L, 0L, 0L, 0L), year = c(112L, 112L, 112L, 
    112L, 112L, 112L), wday = c(5L, 6L, 2L, 3L, 4L, 5L), yday = c(19L, 
    20L, 23L, 24L, 25L, 26L), isdst = c(0L, 0L, 0L, 0L, 0L, 0L
    )), .Names = c("sec", "min", "hour", "mday", "mon", "year", 
"wday", "yday", "isdst"), class = c("POSIXlt", "POSIXt"))), .Names = c("Date", 
"EndTime", "ThresholdTime"), row.names = c(NA, 6L), class = "data.frame")

我希望能够创建一个图表,其中xaxis为Date,yaxis为EndTime,并使用geom_hline绘制ThresholdTime

我可以删除EndTime中的%H和%,将其放入yaxis。基本上,我试图显示EndTime中的哪些数据点违反了ThresholdTime

我面临的问题是:

如果Endtime<-c("2012-01-02 09:00:00")且我的阈值ThresholdTimec("2012-01-01 08:00:00"),我将如何在图表上显示此内容。如果我从%H:%M获取EndTime,它看起来不会违反ThresholdTime,但实际上它违反了阈值。

我很感激任何解决此问题的意见。

1 个答案:

答案 0 :(得分:2)

您的问题是,小时和分钟本身并不能捕获您的所有信息,您还需要一天(或至少相对的一天)。或者另一种思考方式,你需要相对时间。

x$end <- difftime(x$EndTime, as.POSIXct(x$Date), units="hours")
x$thresh <- difftime(x$ThresholdTime, as.POSIXct(x$Date), units="hours")

ggplot不会直接处理difftimes,所以只需转换为它们的数字等效值,这是因为我们强制它是几个小时。然后,它只是标签的一点点格式,看起来像小时和分钟。

ggplot(x, aes(Date, as.numeric(end))) + 
  geom_point() +
  geom_hline(aes(yintercept=as.numeric(thresh))) +
  scale_y_continuous(labels=function(dt) {
    paste0(sprintf("%02d",floor(dt)),":",sprintf("%02d",floor(60*(dt-floor(dt)))))
  })

enter image description here

相关问题