如何在R语言中为Zivot-Andrews单位根测试图添加日期横轴
Zivot-Andrews单位根测试图横轴显示日期的解决方法
问题背景
执行Zivot-Andrews(ZA)单位根测试后,使用自定义绘图函数绘制结果时,横轴显示数字而非预期的日期,即便已经创建了dates日期变量。
问题原因
原代码中使用plot.ts()函数绘制,该函数会自动将日期序列转换为时间序列的数值索引,导致横轴显示数字而非日期格式。
修改后的绘图函数
将plot.ts替换为普通plot()函数,并手动配置日期轴的显示:
plot.ur.za <- function(Time, x, ...) { oldpar <- par(no.readonly = TRUE) on.exit(par(oldpar)) par(mfrow = c(1, 1)) yvals <- sort(c(x@cval, x@tstats)) # 使用普通plot函数,隐藏默认横轴 plot(Time, x@tstats, main = "Zivot-Andrews单位根测试", ylab = "滞后内生变量的t统计量", type = "l", ylim = c(min(yvals), max(yvals)), xaxt = "n", ...) # 自定义日期横轴,设置显示格式 axis.Date(side = 1, at = seq(min(Time), max(Time), by = "1 year"), format = "%Y-%m", las = 2) abline(h = x@cval, col = c("red", "blue", "seagreen")) if (x@teststat < x@cval[3]) { abline(v = Time[x@bpoint], col = "red", lty = 2) } mtext(paste("模型类型:", x@model, sep = " "), side = 1, line = 4) # 调整图例位置,用当前绘图区域的横轴最大值 legend(x = par("usr")[2], y = max(yvals), c("1% 临界值", "2.5% 临界值", "5% 临界值"), col = c("red", "blue", "seagreen"), xjust = 1, yjust = 1, lty = 1, horiz = TRUE, cex = 0.66, bty = "n") }
关键修改点
- 替换
plot.ts为plot,避免自动转换日期为数值索引 - 添加
xaxt="n"隐藏默认横轴,用axis.Date自定义日期显示格式(示例为%Y-%m,可根据需求调整) - 图例x位置改用
par("usr")[2]获取绘图区域的横轴最大值,避免日期格式导致的定位问题
测试代码
library(urca) data(nporg) # 创建日期序列 dates <- seq(as.Date("01/01/1997", format = "%d/%m/%Y"), by = "months", length = length(nporg$cpi)) nporg$dates <- dates gnp <- na.omit(nporg[, c("gnp.r","dates")]) # 执行ZA单位根测试 za.gnp <- ur.za(gnp$gnp.r, model="both", lag=2) # 使用修改后的函数绘图 yrs <- gnp$dates[-length(gnp$dates)] plot.ur.za(Time=yrs, x=za.gnp)
内容的提问来源于stack exchange,提问作者Panagiotis Palaios
相关产品推荐
相关产品推荐

