如何在R中使用绘图时按日期替换X轴上的数字?

hya*_*yat 11 plot r

我想将x实验室作为日期而不是数字.如果你,例如,情节:

 f=c(2,1,5,4,8,9,5,2,1,4,7)
 plot(f)
Run Code Online (Sandbox Code Playgroud)

你可以根据我们有多少值得到x轴数字范围.我如何设置例如我的第一个值为04/01/2012,第二个值为05/01/2012,依此类推,然后在x轴上显示为日期而不是数字!!

我的数据中没有日期,但我知道第一次约会.

提前致谢

Rei*_*son 12

您可以自己标记轴,也可以通过使用"Date"类为您的观察创建日期向量,让R为您完成.这是一个例子:

f <- c(2,1,5,4,8,9,5,2,1,4,7)
dates <- seq(as.Date("04/01/2012", format = "%d/%m/%Y"),
             by = "days", length = length(f))

plot(dates, f)
Run Code Online (Sandbox Code Playgroud)

dates 最终成为:

> dates
 [1] "2012-01-04" "2012-01-05" "2012-01-06" "2012-01-07" "2012-01-08"
 [6] "2012-01-09" "2012-01-10" "2012-01-11" "2012-01-12" "2012-01-13"
[11] "2012-01-14"
Run Code Online (Sandbox Code Playgroud)

情节看起来像这样:

在此输入图像描述

如果您需要更多控制以及标签与您拥有的标签完全相同,则需要禁止绘制x轴,然后使用手动添加axis.Date,例如

plot(dates, f, xaxt = "n")
axis.Date(side = 1, dates, format = "%d/%m/%Y")
Run Code Online (Sandbox Code Playgroud)

哪个产生

在此输入图像描述

您可能还想在那里旋转轴标签,例如使用las = 2.

?axis.Date,?strftime?as.Date为进一步的细节.

使用更好地控制标签的放置 axis.Date

要覆盖刻度线放置的默认启发式,请使用at参数指定刻度线的位置.例如,对于700天的较长日期序列,我们可能会在每个月的开头放置标签:

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)
Run Code Online (Sandbox Code Playgroud)

绘图稍微涉及但不多

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
Run Code Online (Sandbox Code Playgroud)

这导致:

在此输入图像描述

您可以改变这个主题,例如每隔一个月贴标签,其他月份小标记

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 = "2 months")
## new dates for minor ticks
minor <- seq(as.Date("01/02/2012", format = "%d/%m/%Y"), tail(dates, 1),
             by = "2 months")
axis.Date(side = 1, dates, at = labDates, format = "%b %y", las = 2)
## add minor ticks with no labels, shorter tick length
axis.Date(side = 1, dates, at = minor, labels = FALSE, tcl = -0.25)
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
Run Code Online (Sandbox Code Playgroud)

结果

在此输入图像描述

关键是,如果您不喜欢默认值,您可以完全控制轴标记位置,只需创建所需标签/刻度标记位置的日期向量即可.