在ggplot2中绘制时间序列

时间:2013-02-18 14:11:05

标签: r ggplot2

我正在处理时间序列。我的实际数据的前20行如下所示。我希望:

一个。将我的ggplot图设置为特定的时间范围(例如,仅显示07:46:40和07:49:00之间的值)。

湾我还希望改变x轴上刻度线的频率。使用示例详细bwlow我想要在轴上显示整个分钟(但是对于我的正确图表,我希望只显示每小时值。)

感谢上述任何建议。

day3 <- structure(list(Date = c("11/12/2012", "11/12/2012", "11/12/2012", 
                            "11/12/2012", "11/12/2012", "11/12/2012", "11/12/2012", "11/12/2012", 
                            "11/12/2012", "11/12/2012", "11/12/2012", "11/12/2012", "11/12/2012", 
                            "11/12/2012", "11/12/2012", "11/12/2012", "11/12/2012", "11/12/2012", 
                            "11/12/2012", "11/12/2012"), Time = c("07:46:10", "07:46:20", 
                                                                  "07:46:30", "07:46:40", "07:46:50", "07:47:00", "07:47:10", "07:47:20", 
                                                                  "07:47:30", "07:47:40", "07:47:50", "07:48:00", "07:48:10", "07:48:20", 
                                                                  "07:48:30", "07:48:40", "07:48:50", "07:49:00", "07:49:10", "07:49:20"
                            ), Axis1 = c(59L, 651L, 59L, 0L, 22L, 50L, 0L, 0L, 114L, 899L, 
                                         129L, 33L, 21L, 9L, 224L, 135L, 266L, 16L, 59L, 126L), Steps = c(1L, 
                                                                                                          2L, 1L, 0L, 2L, 1L, 0L, 0L, 5L, 15L, 6L, 2L, 2L, 0L, 8L, 5L, 
                                                                                                          16L, 1L, 3L, 8L)), .Names = c("Date", "Time", "Axis1", "Steps"
                                                                                                          ), row.names = 52838:52857, class = "data.frame")
#Creates a new dataframe with a time column.
day3 <- within(day3,{
  posb <- as.POSIXlt(Time,format="%H:%M:%S")
  posb <- NULL  # cleanup
})

library(ggplot2)
g = ggplot(day3, aes(x=strptime(Time, "%H:%M:%S"), y=Axis1)) + geom_line(aes(group = 1)) +
  theme_bw() +
  xlab("Time") + 
  ylab("Activity (Counts per 10 seconds)") + 
  scale_x_datetime(limits=c(as.POSIXct("07:47:50"),as.POSIXct("07:49:10")))


g

修改

如果我想在我的图表上添加一个文本框,我该如何处理时间列? 到目前为止我有:

geom_text(aes(05:00,0),label="Sedentary")

......但目前不想工作。

1 个答案:

答案 0 :(得分:2)

这是你在找什么?

library(scales)
ggplot(day3, aes(x=strptime(Time, "%H:%M:%S"), y=Axis1)) + geom_line(aes(group = 1)) +
  theme_bw() +
  xlab("Time") + 
  ylab("Activity (Counts per 10 seconds)") +
  scale_x_datetime(limits=c(as.POSIXct("07:46:40",format="%H:%M:%S"),as.POSIXct("07:49:00",format="%H:%M:%S")),
                   breaks=date_breaks("1 min"), labels = date_format("%H:%M"))

enter image description here