[英]ACF plot in ggplot2 from a mixed effects model
我正在嘗試在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
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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.