【问题标题】:How to get a "events per month" bar plot in R如何在 R 中获得“每月事件”条形图
【发布时间】:2012-02-12 02:52:33
【问题描述】:

我是 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)

【问题讨论】:

    标签: r statistics plyr audit-logging


    【解决方案1】:

    我会将时间向量放入 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")
    

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

    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 帖子以获取结果图的示例:

    How to create histogram in R with CSV time data?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-29
      • 1970-01-01
      • 2021-07-07
      • 2015-03-20
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      相关资源
      最近更新 更多