[英]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: 所以我想拥有的是:
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.