具有固定限制的日期轴,用于条形图和/或hist

时间:2011-08-30 00:42:21

标签: r statistics scale histogram time-series

给出日期列表

dates <- data.frame(foo = c( 
           "2009-03-15", 
           "2010-04-15", 
           "2011-06-16", 
           "2011-06-17", 
           "2011-06-17", 
           "2011-06-17", 
           "2011-06-17"))

我可以使用以下命令轻松制作直方图:

histo <- hist(as.Date(dates$foo), breaks = "months", freq=TRUE, plot=TRUE)

我也可以制作一个条形图

barplot(histo$counts)

我的问题:

  • 如何创建及时修复的x轴。让我们说从2001-02-03开始到2011-12-13结束?
  • 如何在x轴上添加标签多年,带有年份刻度标记。

注意:我想要一个月度直方图,因此如果可能,建议的解决方案必须保留breaks = months或同等的。

1 个答案:

答案 0 :(得分:2)

我太懒了,无法弄清楚如何使用基本图形来做到这一点。不过,在ggplot2中这很简单:

library(ggplot2)
library(zoo)
ggplot(data = dates,aes(x = as.Date(as.yearmon(foo)))) + 
    geom_bar() + 
    xlim(as.Date(c('2001-01-01','2011-07-20')))

enter image description here

请注意,您描述的内容绝不是直方图,而是条形图。从yearmon转换回Date再转换为Date,可以按月分类,但可以轻松保持日期范围。