我正在嘗試在ggplot2.
library(nlme)
fm2 <- lme(distance ~ age Sex, data = Orthodont, random = ~ 1)
plot(ACF(fm2,resType="normalized"),alpha=0.05)
通過上述函式的結果:

########################## IC ###########################
ic_alpha= function(alpha, acf_res){
return(qnorm((1 (1 - alpha))/2)/sqrt(acf_res$n.used))
}
#################### graphics ###########################
library(ggplot2)
ggplot_acf_pacf= function(res_, lag, label, alpha= 0.05){
df_= with(res_, data.frame(lag, ACF))
lim1= ic_alpha(alpha, res_)
lim0= -lim1
ggplot(data = df_, mapping = aes(x = lag, y = ACF))
geom_hline(aes(yintercept = 0))
geom_segment(mapping = aes(xend = lag, yend = 0))
labs(y= label)
geom_hline(aes(yintercept = lim1), linetype = 2, color = 'blue')
geom_hline(aes(yintercept = lim0), linetype = 2, color = 'blue')
}
######################## result ########################
acf_ts = ggplot_acf_pacf(res_= ACF(fm2,resType="normalized"),
20,
label= "ACF")
但是,我遇到以下錯誤:
Error in sqrt(acf_res$n.used) :
non-numeric argument to mathematical function
我打算得到的是這樣的:

uj5u.com熱心網友回復:
生成的物件ACF沒有名為 的成員n.used。它有一個名為的屬性n.used。所以你的ic_alpha功能應該是:
ic_alpha <- function(alpha, acf_res) {
return(qnorm((1 (1 - alpha)) / 2) / sqrt(attr(acf_res, "n.used")))
}
另一個問題是,由于ic_alpha回傳一個向量,你不會有一對有意義的線,而是每個滯后一對,看起來很亂。相反,模擬基本 R 繪圖方法,我們可以geom_line用來獲得單個曲線對。
ggplot_acf_pacf <- function(res_, lag, label, alpha = 0.05) {
df_ <- with(res_, data.frame(lag, ACF))
lim1 <- ic_alpha(alpha, res_)
lim0 <- -lim1
ggplot(data = df_, mapping = aes(x = lag, y = ACF))
geom_hline(aes(yintercept = 0))
geom_segment(mapping = aes(xend = lag, yend = 0))
labs(y= label)
geom_line(aes(y = lim1), linetype = 2, color = 'blue')
geom_line(aes(y = lim0), linetype = 2, color = 'blue')
theme_gray(base_size = 16)
}
結果是:
ggplot_acf_pacf(res_ = ACF(fm2, resType = "normalized"), 20, label = "ACF")

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/484476.html
