简体   繁体   English

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

[英]Annotate first month with year in ggplot2

Suppose I have a plot like this: 假设我有这样的情节:

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

Here I want to include major lines and labels at every month and minor lines at every week. 在这里,我想在每个月包括主要行和标签,每周包括次要行。 This works well, but now I would like to include the year behind the abbreviated month, but only for the first month of that year in the plot. 这样做效果很好,但现在我想将缩写月份的年份包括在内,但仅限于该年度的第一个月。 Thus, the labels should read sep 2014. okt, nov, dec, jan 2015, feb, mrt.... 因此,标签应该阅读sep 2014. okt,nov,dec,jan 2015,feb,mrt ....

Is this possible? 这可能吗?

You can do it with a custom date formatter to remove duplicated years: 您可以使用自定义日期格式化程序来删除重复的年份:

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

自定义日期图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM