2

我是 R 的新手。

我在这种风格的列表中有时间戳:

 [1] "2011-10-04 17:23:28 CEST" "2011-10-04 17:26:13 CEST" "2011-10-05 16:17:34 CEST" "2011-10-07 09:59:37 CEST"

现在我想绘制一个图表,显示 1 月、2 月等发生了多少事件。

每个时间戳代表一个事件,可能有几个月没有事件(应显示为 0)

4

1 回答 1

2

我会将时间向量放入 data.frame 的列中。下面的示例数据具有一千个时间戳,其中随机时间介于当前时间和两年后。

dat = data.frame(timestamp = Sys.time() + sort(round(runif(1000, (24*3600), (2*365*24*3600)))))

下一步是创建一个新列,用于标识时间戳所在的月份和年份:

dat$month = strftime(dat$time, "%b")
dat$year = strftime(dat$time, "%Y")

count现在我们可以使用包中的数据计算每年每月的时间戳plyr

library(plyr)
timestamps_month = count(dat, vars = c("month","year"))

并使用 ggplot2 创建直方图:

library(ggplot2)
ggplot(data = timestamps_month) + geom_bar(aes(x = month, y = freq, fill = year), stat="identity", position = "dodge")

有关结果图的示例,请参见此 SO 帖子:

如何使用 CSV 时间数据在 R 中创建直方图?

于 2012-01-17T11:42:19.143 回答