【问题标题】:histgramming dates with unequal bins in ggplotggplot中具有不等分箱的直方图日期
【发布时间】:2012-09-05 21:48:23
【问题描述】:

我试图让 ggplot 生成一个带有 3 个月宽的箱的直方图。不是 90 天,而是 3 个月。就天数而言,这是一个不等宽的分箱。请注意,每隔 3 个月的刻度线可以正常工作。这是我遇到问题的 bin 宽度。这里有很多讨论,但我找不到解决方案。

Understanding dates and plotting a histogram with ggplot2 in R

这是问题的陈述。请注意,我显然可以在 ggplot 之外聚合结果,然后将它们绘制出来,也许是 ggplot 中的因素。但我一直在寻找一个全 ggplot 解决方案。

set.seed(seed=1)
dts<-as.Date('2012-01-01') + round(365*rnorm(500))
dts<-data.frame(d=dts)
g<-ggplot(dts,aes(x=d, y=..count..))

#this isnt what I want.  It is 90 days, not 3 months.
#Setting binwidth=' 3 months' also doesnt work
g + geom_histogram(fill='blue',binwidth=90) +
    scale_x_date(breaks = date_breaks('3 months'),  #seq(as.Date('2008-1-1'), as.Date('2012-3-1'), '3 month'),
                 labels = date_format("%Y-%m"),
                 limits = c(as.Date('2010-1-1'), as.Date('2014-1-1'))) +
    opts(axis.text.x = theme_text(angle=90))

#this doesnt work either.
#get:   stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.
#        Error in `+.Date`(left, right) : binary + is not defined for Date objects
g + geom_bar(fill='blue') +
    stat_bin(breaks=seq(as.Date('2010-1-1'), as.Date('2014-1-1'), '3 month')) +
    scale_x_date(breaks = date_breaks('3 months'),  #seq(as.Date('2008-1-1'), as.Date('2012-3-1'), '3 month'),
                 labels = date_format("%Y-%m"),
                 limits = c(as.Date('2010-1-1'), as.Date('2014-1-1'))) +
    opts(axis.text.x = theme_text(angle=90))

也许答案是:ggplot 不会创建 3 个月宽(或 N 个月宽)的 bin。

【问题讨论】:

  • 我认为你应该在ggplot 之外进行聚合......专家的共识(例如在 ggplot 邮件列表上)似乎是一旦事情变得足够复杂,最好做自己聚合,然后将结果输入ggplot(使用适当的geoms,您可以使结果看起来与ggplot 绘制它们的方式完全相同,如果它能够执行不相等的 bin宽度)而不是在ggplot(毕竟这主要是一个plotting包)中完成后空翻。
  • 为什么你的限制与你的休息时间相差如此之大???
  • 感谢本的指导。 DWin:我不明白为什么没有严格执行这些限制,以及为什么会有一些悬垂,并且在视觉上看起来每端都有一个半宽的箱子。也许这与我的限制和标签为 3 个月但 binwidth 为 90 天有关。

标签: r ggplot2


【解决方案1】:

如您所见,stat_bin 将允许指定 bin 边缘。但在处理日期时,往往需要手动将值转换为内部刻度才能工作。此外,在您的第二个示例中,您同时拥有一个 geom_bar 和一个 stat_bin,它们正在绘制两个不同的图层。这是一个工作版本:

g + stat_bin(breaks=as.numeric(seq(as.Date('2010-1-1'), 
                                   as.Date('2014-1-1'), '3 month')),
             fill = "blue",
             position = "identity") +
    scale_x_date(breaks = date_breaks('3 months'),
                 labels = date_format("%Y-%m"),
                 limits = c(as.Date('2010-1-1'), as.Date('2014-1-1'))) +
    opts(axis.text.x = theme_text(angle=90))

请注意,我已将 breaks 参数包装到 stat_binas.numeric。另外,我在stat_bin 中添加了一个position="identity" 参数以消除有关不等箱宽度的警告(因为只有一组,所以不需要与任何东西堆叠)。

【讨论】:

    猜你喜欢
    • 2022-12-21
    • 2017-01-08
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    相关资源
    最近更新 更多