R使用ggplot2绘制Chow Test结果报object 'dd' not found错误如何解决
报错原因
dd是你在dlply、ddply的匿名函数内部定义的局部参数,仅在函数运行的临时作用域内有效,函数执行结束后就会被销毁,全局环境下的ggplot调用自然无法识别该对象。
修复方案
你要添加的红色竖线对应固定日期2021-05-05 15:00:00 UTC,直接在geom_vline中传入这个日期值即可,不需要调用不存在的dd对象:
# 原有计算逻辑无需改动 chows<-plyr::dlply(dat1,~variable,function(dd){ point=((1:nrow(dd))[dd$PricingDate==as.POSIXct("2021-05-05 15:00:00 UTC")]) chowtest<-strucchange::sctest(data=dd,value~1,type="Chow",point=point) fs<-strucchange::Fstats(data=dd,formula=value~1) breaks<-strucchange::breakpoints(value~1,data=dd)$breakpoints list(chowtest=chowtest,fs=fs,breaks=breaks) }) breaks<-plyr::ddply(dat1,~variable,function(dd){ data.frame(breaks=dd$PricingDate[strucchange::breakpoints(value~1,data=dd)$breakpoints]) }) # 仅修改红色竖线对应的geom_vline行即可 graph<-ggplot(data=dat1,aes(x=PricingDate,y=value))+ geom_line()+ # 直接传入固定日期作为截距,所有分面都会自动生成这条竖线 geom_vline(xintercept = as.POSIXct("2021-05-05 15:00:00 UTC"), color="red", alpha=.5, size=3)+ geom_vline(data=breaks,aes(xintercept=breaks))+ facet_wrap(~variable,scales="free")
可选补充方案
如果你仅需要在存在该日期的分组分面显示红色竖线,可以提前生成对应参考表传入geom_vline:
# 生成每个variable对应的指定日期参考表 ref_dates <- dat1[dat1$PricingDate == as.POSIXct("2021-05-05 15:00:00 UTC"), "variable", drop = FALSE] ref_dates$cutoff_date <- as.POSIXct("2021-05-05 15:00:00 UTC") # 绘图时指定data参数 graph<-ggplot(data=dat1,aes(x=PricingDate,y=value))+ geom_line()+ geom_vline(data = ref_dates, aes(xintercept = cutoff_date), color="red", alpha=.5, size=3)+ geom_vline(data=breaks,aes(xintercept=breaks))+ facet_wrap(~variable,scales="free")
内容的提问来源于stack exchange,提问作者max0506
相关产品推荐
相关产品推荐

