2013-01-08 129 views
8

我有這樣一個數據幀的時間:繪製僅使用GGPLOT2

head(yy) 
    Team  Date STime ETime 
1 A 2012-03-06 07:03 10:13 
2 A 2012-03-06 07:03 10:13 
3 A 2012-03-06 07:03 10:13 
4 A 2012-03-06 07:03 10:13 
5 A 2012-03-06 07:03 10:13 
6 A 2012-03-06 07:03 10:13 

dput(YY)

dput(yy) 
structure(list(Team = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "A", class = "factor"), 
Date = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "2012-03-06", class = "factor"), 
STime = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "07:03", class = "factor"), 
ETime = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "10:13", class = "factor")), .Names = c("Team", 
"Date", "STime", "ETime"), class = "data.frame", row.names = c(NA, 
-50L)) 

我喜歡看的y軸從00:00 23:59在增加2小時,並能夠在STime值上繪製紅線。

我的財產以後這樣的,但它看起來不正確:

ggplot(yy, aes(Date, ETime, group="Team")) + geom_jitter(size=0.05) + facet_wrap(~ Team) + geom_hline(yintercept=yy$Stime, colour="red", size=2) 

enter image description here 你會如何在GGPLOT2做到這一點?有人能給我指示/啓動我在正確的方向嗎?

問候,

+2

你可以發佈結果'dput(df)'(或'dput(head(df))'如果它太大了,我們可以重現你的數據嗎? –

+0

@DavidRobinson,我只是放置了輸出輸出。 – user1471980

+0

您的數據沒有變化。如果你只是試圖製作一個插圖,你應該看一看[inkscape](http://inkscape.org/),它是一個很棒的免費軟件 - 比如R. –

回答

6

您必須將您的時間格式化爲實際時間。現在他們是因素(用str(yy)檢查你的數據幀)。繪製ETime時,單次繪製爲1並標記爲「10:13」。因此,下面的解決方案首先將字符串「10:13」轉換爲時間(strptime),然後將其轉換爲POSIXct,或自原點(1/1/1970)以來的秒數。

library(ggplot2); library(scales) 

#Convert date string into POSIXct format 
yy$STime <- as.POSIXct(strptime(yy$STime, format = "%H:%M", tz = "UTC")) 
yy$ETime <- as.POSIXct(strptime(yy$ETime, format = "%H:%M", tz = "UTC")) 

#Define y-axis limits 
lims <- as.POSIXct(strptime(c("0:00","23:59"), format = "%H:%M", tz= "UTC"))  

ggplot(yy, aes(Date, ETime, group="Team")) + geom_jitter(size=1) + facet_wrap(~ Team) + 
    geom_hline(data = yy, aes(yintercept= as.numeric(STime)), colour="red", size=2) + 
    scale_y_datetime(limits =lims, breaks=date_breaks("2 hour"), 
        labels=date_format("%H:%M", tz = "UTC")) 

datetime y-axisgeom_line to date axis注意。

請注意您的時區。否則,R/ggplot將根據當地時區對事物進行格式化。