14

所以我有一组这样的时间戳:

datetime<-c("2011-09-28 03:33:00", "2011-08-24 13:41:00", "2011-09-19 16:14:00", "2011-08-18 11:01:00", "2011-09-17 06:35:00", "2011-08-15 12:48:00")

我只想制作时间的直方图。我所做的是在空间拆分列以仅获取时间,然后转换回 POSIXct 对象以便 qplot 绘制它:

library(ggplot2, stringr)    
qplot(as.POSIXct(strptime((str_split_fixed(as.character(time), " ", 2)[,2]), "%H:%M:%S")))

然而,输出as.POSIXct(strptime((str_split_fixed(as.character(datetime), " ", 2)[,2]), "%H:%M:%S"))

"2011-10-04 03:33:00 PDT" "2011-10-04 13:41:00 PDT" "2011-10-04 16:14:00 PDT" "2011-10-04 11:01:00 PDT" "2011-10-04 06:35:00 PDT" "2011-10-04 12:48:00 PDT"

qplot 绘制我想要的图,但这对我来说似乎是一个令人费解的黑客攻击。当然有更好的方法来做到这一点?我可以转换为纪元时间并绘制它,但我试图避免将其作为额外的步骤。

更大的问题是,“我如何控制 strptime 的输出?”

4

2 回答 2

15

这种方法怎么样?

require("ggplot2")
dtstring <- c(
  "2011-09-28 03:33:00", "2011-08-24 13:41:00", "2011-09-19 16:14:00",
  "2011-08-18 11:01:00", "2011-09-17 06:35:00", "2011-08-15 12:48:00"
)
dtPOSIXct <- as.POSIXct(dtstring)

# extract time of 'date+time' (POSIXct) in hours as numeric
dtTime <- as.numeric(dtPOSIXct - trunc(dtPOSIXct, "days"))

p <- qplot(dtTime) + xlab("Time slot") + scale_x_datetime(format = "%S:00")
print(p)

计算dtPOSIXct - trunc(dtPOSIXct, "days")提取 POSIXct 类对象的时间(以小时为单位)。

情节(p)

对于ggplot2-0.9.1

require("ggplot2")
require("scales")
dtstring <- c(
  "2011-09-28 03:33:00", "2011-08-24 13:41:00", "2011-09-19 16:14:00",
  "2011-08-18 11:01:00", "2011-09-17 06:35:00", "2011-08-15 12:48:00"
)
dtPOSIXct <- as.POSIXct(dtstring)

# extract time of 'date+time' (POSIXct) in hours as numeric
dtTime <- as.numeric(dtPOSIXct - trunc(dtPOSIXct, "days"))

p <- qplot(dtTime) + xlab("Time slot") +
     scale_x_datetime(labels = date_format("%S:00"))
print(p)

对于ggplot2-0.9.3.1

require("ggplot2")
require("scales")
dtstring <- c(
  "2011-09-28 03:33:00", "2011-08-24 13:41:00", "2011-09-19 16:14:00",
  "2011-08-18 11:01:00", "2011-09-17 06:35:00", "2011-08-15 12:48:00"
)
dtPOSIXct <- as.POSIXct(dtstring)

# extract time of 'date+time' (POSIXct) in hours as numeric
dtTime <- as.numeric(dtPOSIXct - trunc(dtPOSIXct, "days"))
class(dtTime) <- "POSIXct"

p <- qplot(dtTime) + xlab("Time slot") +
     scale_x_datetime(labels = date_format("%S:00"))
print(p)
于 2011-10-05T03:03:49.323 回答
4

只需按预期使用基本工具:

dtstring <- c("2011-09-28 03:33:00", "2011-08-24 13:41:00", "2011-09-19 16:14:00", "2011-08-18 11:01:00", "2011-09-17 06:35:00", "2011-08-15 12:48:00")
datetime <- as.POSIXct(dtstring)
library(ggplot2)
qplot(datetime)

您的字符串的格式是使用 解析的默认格式as.POSIXct,请参阅?strptime了解详细信息,或者如果您有除此格式之外的其他内容。

如果您想从日期时间值中获取特定的字符串格式,请使用format,如

format(datetime, "%d-%b")
[1] "28-Sep" "24-Aug" "19-Sep" "18-Aug" "17-Sep" "15-Aug"

再次,请参阅?strptime详细信息。如果您真的想丢弃时间值,可以使用Date该类。请注意,日期时间或日期需要它们的完整结构,任何其他表示只是格式化文本。

qplot(as.Date(datetime))

于 2011-10-05T00:38:56.417 回答