简体   繁体   English

ggplot2中的自定义日期轴

[英]custom date axis in ggplot2

I am trying to generate a plot in ggplot2 with customized ticks. 我正在尝试使用自定义刻度在ggplot2生成一个图。 The problem is if I choose eg date_breaks = "5 years" , the plot will start the labeling at the very last date year, and go back in 5 year intervals, but miss on the first date. 问题是,如果我选择例如date_breaks = "5 years" ,则绘图将在最后一个日期年份开始标注,并以5年间隔返回,但在第一个日期错过。 This makes sense, but what if I would like to show the first date as well so people see the beginning of my plot? 这是有道理的,但是如果我也想显示第一个日期,以便人们看到我的情节的开始怎么办? Moreover, the ticks in between are not shown. 此外,未显示中间的刻度线。 So what I would like to have is: 所以我想拥有的是:

  • 5 year intervals, each labelled (eg assume a label at 1988) and also marked on the axis 5年间隔,每次标记(例如,假设在1988年标记),并在轴上标记
  • 1 year marks not labelled in between (eg if we assume 1988 is labelled, 1989 to 1992 should only be marked on the axis with ticks, but not be labelled) 1年标记未在其间标记(例如,如果我们假设1988被标记,则1989至1992仅应在刻度线上标有刻度,而不应标记)
  • a custom start date for the labeling and a custom end date for the labeling. 标签的自定义开始日期和标签的自定义结束日期。 Now of course both is likely not possible if numbers are not in the sequence of 5 years. 现在当然,如果数字不在5年的序列中,那么两者都不可能。 In this case, it probably makes sense to decide for either a custom start/end date and do the labeling from there. 在这种情况下,决定自定义开始/结束日期并从那里进行标签可能很有意义。 Let me know what you think is the best solution in this case. 让我知道您认为在这种情况下最好的解决方案。

MWE: MWE:

set.seed(1)
test <- data.table(x = rnorm(29*2),var=c(rep("x1",29),rep("x2",29)),
                   time=rep(seq(as.Date("1983/12/31"),as.Date("2011/12/31"), "year"),2))
library(ggplot2);library(scales)
ggplot(data=test,aes(x=time, y=x, colour=var)) + 
geom_line() + scale_x_date(date_labels="%Y",date_breaks = "5 years",
                             date_minor_breaks="1 year")

You could just define breaks and labels manually which you can adjust arbitrarily. 您可以手动定义中断和标签,可以随意调整。

dts <- as.Date(paste0(seq(1980, 2015, 1), "-01-01"))
x.labs <- substr(as.character(dts), 1, 4)
x.labs[5:length(dts - 2) %% 5 != 0] <- ""  # modulo 5

library(ggplot2);library(scales)
ggplot(data=test, aes(x=time, y=x, colour=var)) + 
  geom_line() + 
  scale_x_date(breaks=dts, labels=x.labs)

Yielding 生产

在此处输入图片说明

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

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