如何获得“每月事件"? R中的条形图 [英] How to get a "events per month" bar plot in R

查看:105
本文介绍了如何获得“每月事件"? R中的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在R中成为新手.

我在此样式的列表中有时间戳记:

I've got timestamps in a list in this style:

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

现在,我想绘制一个图表,向我显示一月,二月等发生了多少事件.

Now I want to plot a graph which shows me how many events occur in january, february and so on.

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

Every timestamp represents one event and there may be months without an event (that should be shown as 0)

推荐答案

我会将时间向量放入data.frame的列中.下面的示例数据具有一千个时间戳,其当前时间与从现在开始的两年之间是随机时间.

I would put the vector of times into a column of a data.frame. The example data below has a thousand timestamps with a random time between the current time and two year from now.

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

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

Next step is to create a new column that identifies which month and year the timestamp is in:

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

现在,我们可以使用plyr软件包中的count来计算每年每个月的时间戳记.

Now we can count the timestamps per month for each year using count from the plyr package.

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

并使用ggplot2创建直方图:

And create the histogram with ggplot2:

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

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

See this SO post for an example of how the resulting plot looks like:

如何在R是否包含CSV时间数据?

这篇关于如何获得“每月事件"? R中的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆