2013-01-08 124 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将根据当地时区对事物进行格式化。