在ggplot2中用年份注释第一个月 [英] Annotate first month with year in ggplot2

查看:66
本文介绍了在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"))

在这里,我希望每个月都包含主要行和标签,每周要包含次要行.这很好用,但是现在我想将缩写月份的后一年包括在内,但仅在该情节中该年的第一个月.因此,标签应显示2014年9月.okt,nov,dec,jan,jan 2015,feb,mrt....

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....

这可能吗?

推荐答案

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

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

这篇关于在ggplot2中用年份注释第一个月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆