8

我有一个这样的数据框:

 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

输出(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)

在此处输入图像描述 您将如何在 ggplot2 中执行此操作?有人可以给我指点/让我朝着正确的方向前进吗?

问候,

4

1 回答 1

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") )

日期时间 y 轴 注意geom_line 到日期轴

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

于 2016-02-06T01:10:36.903 回答