【问题标题】:R ggplot by month and values group by WeekR ggplot 按月和值按周分组
【发布时间】:2016-05-19 17:15:39
【问题描述】:

使用 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 周,而是显示整个月。

你知道我必须改变什么才能得到我想要的吗?

感谢您的帮助

【问题讨论】:

  • 我一直在创造这样的东西,但我不明白你想要什么。例如,一个月通常没有 4 周,但该月几乎总是超过 5 周。
  • 嗨,迈克,我同意你关于 4 或 5 周的看法。我的想法是简单地按周或按天(1 到 30 或 31)对数据进行分组,如果更容易的话)。像这样dl.dropboxusercontent.com/u/96280295/r_group_by_week
  • 嗨,尼科,迈克。最后我已经能够做我想要的(dl.dropboxusercontent.com/u/96280295/Rplot_datemonth.png)。我唯一不知道的事情是按月份(一月、二月等)而不是按字母(a、b、c 等)排序
  • 我在回答中为您订购了几个月。有机会被录取吗?
  • 有机会被录取吗?

标签: r ggplot2 time-series


【解决方案1】:

好的,既然我看到了你想要的,我写了一个小程序来说明它。您的月份顺序问题的关键是将月份设置为 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)

产量:

(顺便说一句,我很自豪我在没有lubridate 的情况下做到了这一点......)

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 2021-03-03
      相关资源
      最近更新 更多