仅使用ggplot2绘制时间

时间:2013-01-08 16:48:07

标签: r 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))

我喜欢在2小时内从00:00 23:59看到y轴,并且能够在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中做到这一点?有人可以给我指点/让我朝着正确的方向前进吗?

此致

1 个答案:

答案 0 :(得分:6)

您必须将时间格式化为实际时间。现在它们是因素(使用str(yy)检查数据框)。绘制ETime时,将单个时间绘制为1并标记为“10:13”。因此,下面的解决方案首先将字符串“10:13”转换为时间(strptime),然后将其转换为POSIXct,或者自原点(1970年1月1日)起的秒数。

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-axis 关于geom_line to date axis的注意事项。

也要注意你的时区。否则R / ggplot将根据您当地的时区格式化。