【问题标题】:Creating month-sized bins with ggplot2 in r在 r 中使用 ggplot2 创建月大小的 bin
【发布时间】:2014-04-09 02:47:03
【问题描述】:

我有一组数据需要在 ggplot2 中绘制。这是时间安排的。这是数据集:

testset <- data.table(Date=as.Date(c("2013-07-02","2013-08-03","2013-09-04","2013-10-05","2013-11-06","2013-07-03","2013-08-04","2013-09-05","2013-10-06","2013-11-07")), Action = c("A","B","C","D","E","B","A","B","C","A","B","E","E","C","A"), rating = runif(30))

我正在做的是绘制它并使用 scale_x_date 将过时的数据放在图表上。但是,当我这样做时,它不会将其放入月大小的垃圾箱中。相反,它会在执行操作的当天将其分箱。

ggplot(testset, aes(Date, fill=Action)) + geom_bar(position="dodge") + scale_x_date(labels = date_format("%b %Y"), breaks = date_breaks(width = "months"))

我想做的是将每个月的所有日期放入一个容器中,然后绘制图表。在浏览 StackOverflow 时我没有找到任何解决方案,并且在浏览 ggplot2 或 scale_x_date 的文献时没有任何问题出现。我不反对使用 lubridate 或 zoo,如果它们可以提供我正在寻找的输出。

提前致谢!

编辑:从@mnel 看到下面的答案后,我最终发布了a question about how to modify plots。在@tonytonov 给我的帮助和@mnel 给我的帮助之间,我想出了一个解决方案。

ggplot(testset, aes(as.factor(as.yearmon(Date)), fill=Action)) + 
geom_bar(position='dodge') + xlab("Date") + ylab("Count")

这最终给了我这个图表:

谢谢你们!

【问题讨论】:

    标签: r date plot ggplot2 data.table


    【解决方案1】:

    您可以使用 zoo 包中的 yearmon 类。 zoo 包中有一个scale_..._yearmon 函数,其工作原理与scales 包中的scale_x_date 函数类似

    library(zoo)
    ggplot(testset, aes(as.yearmon(Date), fill=Action)) + 
      geom_bar(position = position_dodge(width  = 1/12), 
               binwidth=1/12, colour='black') + 
      scale_x_yearmon()
    

    【讨论】:

    • 有什么方法可以强制绘图删除每个月未使用的值并自动创建大小合适的条形图?因为对于我创建的所有其他情节,这就是行为,我希望它适合。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多