Arn*_*ibu 3 r time-series ggplot2
使用 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
Run Code Online (Sandbox Code Playgroud)
我为这个数据集创建了另外两个基于 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
Run Code Online (Sandbox Code Playgroud)
现在我想为每个月创建一个条形图,其中我有按周聚合的计数值的总和。因此,例如一年,我将有 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)
Run Code Online (Sandbox Code Playgroud)
到目前为止,我的情节看起来像这样 https://dl.dropboxusercontent.com/u/96280295/Rplot.png
如您所见,x 轴与我所寻找的不同。它不是只显示第 1、2、3 和 4 周,而是显示整个月。
你知道我必须改变什么才能得到我想要的吗?
谢谢你的帮助
好的,现在我看到了你想要的东西,我写了一个小程序来说明它。月顺序问题的关键是使月 afactor的级别按正确顺序排列:
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)
Run Code Online (Sandbox Code Playgroud)
产量:
(顺便说一句,我很自豪我没有这样做lubridate……)