在ggplot2中用年份注释第一个月

时间:2014-12-09 13:52:37

标签: r ggplot2

假设我有这样的情节:

DF <- data.frame(date=Sys.Date() - (-100):100, y=rnorm(201))
library("ggplot2")
library(scales)
ggplot(DF, aes(x=date, y=y)) +
 geom_point() +
 scale_x_date(breaks = "1 month", minor_breaks = "1 week", labels=date_format("%b"))

在这里,我希望每个月都包含主要行和标签,每周都包含次要行。这样做效果很好,但现在我想将缩写月份的年份包括在内,但仅限于该年度的第一个月。因此,标签应该阅读2014年sep。okt,nov,dec,jan 2015,feb,mrt ....

这可能吗?

1 个答案:

答案 0 :(得分:13)

您可以使用自定义日期格式化程序来删除重复的年份:

my_date_format <- function()
{
   function(x)
   {
       m <- format(x,"%b")
       y <- format(x,"%Y")
       ifelse(duplicated(y),m,paste(m,y))
   }
}

ggplot(DF, aes(x=date, y=y)) +
 geom_point() +
 scale_x_date(breaks = "1 month", minor_breaks = "1 week", labels=my_date_format())

Custom date plot

相关问题