2013-02-18 383 views
1

我正在處理時間序列。下面顯示了我的真實數據的前20行。我希望:在ggplot2中繪製時間序列

a。將我的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

這是你在找什麼?

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

+0

非常感謝@juba - 這是偉大的。我有關於繪製時間序列的最後一個問題(我已經添加到我的原始問題)。任何建議都會很棒! – 2013-02-18 14:56:44

+0

嘗試類似'geom_text(aes(x = as.POSIXct(「07:48:00」,format =「%H:%M:%S」),y = 250),label =「foo」) – juba 2013-02-18 15:03:30

+0

這很好 - 謝謝@ juba。 – 2013-02-18 15:12:35