You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 12:22:49