繁体   English   中英

R如何标记不连续的X轴刻度

[英]R how to label non-sequential x-axis ticks

我正在跟踪@Gavin Simpson对先前有关x轴刻度标签的问题的答复,以及有关非顺序刻度标签的问题。 这是他设置问题的响应示例:

set.seed(53)
f <- rnorm(700, 2)
dates <- seq(as.Date("04/01/2012", format = "%d/%m/%Y"),
             by = "days", length = length(f))
head(f)
op <- par(mar = c(7,4,4,2) + 0.1) ## more space for the labels
plot(dates, f, xaxt = "n", ann = FALSE)
labDates <- seq(as.Date("01/01/2012", format = "%d/%m/%Y"), tail(dates, 1),
                by = "months")
axis.Date(side = 1, dates, at = labDates, format = "%b %y", las = 2)
title(ylab = "f") ## draw the axis labels
title(xlab = "dates", line = 5) ## push this one down a bit in larger margin
par(op) ## reset margin

但是,我不想只标出从“ Jan 12”开始到“ Dec 13”结束的一组有序的x轴刻度标签,我只希望标出几个非顺序且长度与f不同的日期,例如3月3日,2012年,2012年4月27日,2012年10月20日和2013年5月8日,其余的情节仍然存在。 因此,我设置了一个要呼叫的日期向量,但之后就被绊倒了:

set.seed(53)
f <- rnorm(700, 2)   # the count doesn't matter
MyDates<-c("03/03/12", "04/27/13","10/20/12", "05/08/13")   # non-sequential char string of dates not equal to f
plot(MyDates, f, xaxt = "n", ann = FALSE)
axis.Date(1, MyDates, at=c(1,length(MyDates), ??????))   #not complete and not right

因此,我的问题是如何标记一组长度与数据长度不同的非顺序x轴刻度线?

我还想在选择的日期添加垂直线,我知道这可能是使用abline() ,但是由于我正在axis.Date解决这一问题而尚未到达。

首先,将您选择的日期从character转换为Date (使用正确的格式字符串):

MyDates <- as.Date(MyDates, format = "%m/%d/%y")
# [1] "2012-03-03" "2013-04-27" "2012-10-20" "2013-05-08"

class(MyDates)
# [1] "Date"

然后,您可以仅在这些点上添加带有刻度的轴:

axis.Date(side = 1, at = MyDates, format = "%b %y", las = 2)

短轴看起来很丑? 添加第一个和最后一个日期:

axis.Date(side = 1, at = c(min(dates), MyDates, max(dates)), format = "%b %y", las = 2)

是否想拉伸轴但没有第一个/最后一个标签? 不要打印它们:

axis.Date(side = 1, at = c(min(dates), MyDates, max(dates)), 
    labels = c("", format(MyDates, "%b %y"), ""), las = 2)

或者,先绘制一个没有标签的长轴:

axis.Date(side = 1, at = c(min(dates), max(dates)), labels=FALSE)
axis.Date(side = 1, at = MyDates, format = "%b %y", las = 2)

垂直线:

abline(v=MyDates)
abline(v=MyDates, lty="dashed", col="red")
# etc.

暂无
暂无

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

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