R ggplot按月和值组按周

时间:2016-02-09 16:13:47

标签: r ggplot2 time-series

使用ggplot2,我想创建一个多重绘图(facet_grid),其中每个绘图是该月的每周计数值。

我的数据是这样的:

   day_group count 
1 2012-04-29   140
2 2012-05-06 12595
3 2012-05-13 12506
4 2012-05-20 14857

我为此数据集创建了另外两个基于day_group的月份和周的列:

   day_group count Month Week
1 2012-04-29   140   Apr   17
2 2012-05-06 12595   May   18
3 2012-05-13 12506   May   19
4 2012-05-20 14857   May   2

现在我希望每个月都能创建一个条形图,其中我有按周聚合的计数值的总和。因此,例如一年,我将有12个地块,4个酒吧(每周一个)。

以下是我用来生成情节的内容:

ggplot(data = count_by_day, aes(x=day_group, y=count)) +
stat_summary(fun.y="sum", geom = "bar") + 
scale_x_date(date_breaks = "1 month",  date_labels = "%B") +
facet_grid(facets = Month ~ ., scales="free", margins = FALSE)

到目前为止,我的情节看起来像这样 https://dl.dropboxusercontent.com/u/96280295/Rplot.png

正如你所看到的那样,x轴并不像我正在寻找的那样。它不是仅显示第1,2,3和4周,而是显示所有月份。

你知道我必须改变什么来得到我正在寻找的东西吗?

感谢您的帮助

2 个答案:

答案 0 :(得分:4)

好的,现在我看到了你想要的东西,我写了一个小程序来说明它。您的月份订单问题的关键是使月份为factor,其级别的顺序正确:

library(dplyr)
library(ggplot2)

#initialization
set.seed(1234)
sday <- as.Date("2012-01-01")
eday <- as.Date("2012-07-31")

# List of the first day of the months
mfdays <- seq(sday,length.out=12,by="1 month")

# list of months - this is key to keeping the order straight
mlabs <- months(mfdays)

# list of first weeks of the months
mfweek <- trunc((mfdays-sday)/7)
names(mfweek) <- mlabs

# Generate a bunch of event-days, and then months, then week numbs in our range
n <- 1000
edf <-data.frame(date=sample(seq(sday,eday,by=1),n,T))
edf$month <- factor(months(edf$date),levels=mlabs)   # use the factor in the right order
edf$week <- 1 + as.integer(((edf$date-sday)/7) - mfweek[edf$month])

# Now summarize with dplyr
ndf <- group_by(edf,month,week) %>% summarize( count = n() )

ggplot(ndf) + geom_bar(aes(x=week,y=count),stat="identity")  + facet_wrap(~month,nrow=1)

产量:

enter image description here

(顺便说一句,我很自豪我没有lubridate ...)

答案 1 :(得分:1)

我认为你必须这样做,但我不确定我理解你的问题:

ggplot(data = count_by_day, aes(x=Week, y=count, group= Month, color=Month))