2017-05-16 86 views
1

下面是一個例子數據:如何製作線和點圖的日期和時間的範圍r中

> WakeTime <- strptime(c("2017/5/1 08:12", "2017/5/1 08:30", "2017/5/2 
08:00", "2017/5/2 04:50"), format = "%Y/%m/%d %H:%M") 
> SleepTime <- strptime(c("2017/5/1 20:30", "2017/5/1 21:13", "2017/5/2 
22:15", "2017/5/3 01:00"), format = "%Y/%m/%d %H:%M") 

> timetable <- data.frame(WakeTime,SleepTime);timetable 
      WakeTime   SleepTime 
1 2017-05-01 08:12:00 2017-05-01 20:30:00 
2 2017-05-01 08:30:00 2017-05-01 21:13:00 
3 2017-05-02 08:00:00 2017-05-02 22:15:00 
4 2017-05-02 04:50:00 2017-05-03 01:00:00 

我試圖汲取從WakeTimeSleepTime線的圖,其中x是24小時,y是月和日。我嘗試了很多方法,但仍然遇到了幾個小時的麻煩。

如果你需要額外的代碼:

> WMonthDay <- as.Date(WakeTime,format = "%b/%d") 
> SMonthDay <- as.Date(SleepTime,format = "%b/%d") 
> Whm <- format(WakeTime, "%H:%M") 
> Shm <- format(SleepTime, "%H:%M") 
> Supertimetable <- data.frame(WMonthDay,SMonthDay,Whm,Shm);Supertimetable 
    WMonthDay SMonthDay Whm Shm 
1 2017-05-01 2017-05-01 08:12 20:30 
2 2017-05-01 2017-05-01 08:30 21:13 
3 2017-05-02 2017-05-02 08:00 22:15 
4 2017-05-02 2017-05-03 04:50 01:00 

附:無論如何,WakeTimeSleepTime作爲兩個不同的顏色點在同一個陰謀?

回答

3

使用這些輔助功能

library(hms) 
date_only <- function(x) 
    as.Date(strftime(x, "%Y-%m-%d")) 
time_only <- function(x) 
    as.hms(x-date_only(x)) 

你可以做這樣的事情

ggplot(timetable) + 
geom_segment(aes(x=time_only(WakeTime), xend=time_only(SleepTime), 
    y=date_only(WakeTime), yend=date_only(SleepTime))) + 
geom_point(aes(x=time_only(WakeTime), y=date_only(WakeTime)), col="green") + 
geom_point(aes(x=time_only(SleepTime), y=date_only(SleepTime)), col="blue") + 
scale_x_time() + 
scale_y_date() + 
labs(x="Time", y="Date") 

enter image description here

+0

我得到了這樣的警告:'警告消息: 1:在as.hms(X - date_only(x)): 「 - 」的不兼容方法(「-.POSIXt」,「 - Date」)' –

+0

這只是一個警告。如果你願意,我想你可以做'time_only < - function(x)as.hms(x-as.POSIXct(date_only(x)))''。 – MrFlick

+0

太好了。這是完美的!謝謝。 –

相關問題