开发者

date axis with fixed limit for barplot and/or hist

Given a list of dates

dates <- data.frame(foo = c开发者_JAVA技巧( 
           "2009-03-15", 
           "2010-04-15", 
           "2011-06-16", 
           "2011-06-17", 
           "2011-06-17", 
           "2011-06-17", 
           "2011-06-17"))

I can make a histogram easily with the following command:

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

I can also make a barplot

barplot(histo$counts)

My issue:

  • How do I create an x-axis which is fixed in time. Let's say starting at 2001-02-03 and finishing at 2011-12-13?
  • How do I add labels on the x-axis for years only, with years tick marks.

Note: I want a monthly histogram, so the proposed solution if possible must preserve the breaks = months or equivalent.


I'm too lazy to figure out how to do this using base graphics. It's pretty easy in ggplot2, though:

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')))

date axis with fixed limit for barplot and/or hist

Note that what you describe is by no means a histogram, but a bar chart. Converting back and forth from yearmon and then back to Date gives you the binning by month, but makes keeping the date scale easy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜