ARIMA样本内预测test_forecast在Shiny应用中无绘图输出问题
问题原因
- TSstudio包的
test_forecast()函数默认返回plotly交互式绘图对象,不兼容静态绘图渲染逻辑 - 原代码用的
plotOutput()+renderPlot()组合仅支持渲染base R、ggplot2生成的静态图,无法加载plotly对象,因此没有绘图输出
修复方案
仅需要修改UI和服务端的渲染控件类型即可:
- UI端将
plotOutput("out")替换为plotlyOutput("out"),适配交互式绘图的输出容器 - 服务端将
renderPlot({})替换为renderPlotly({}),用来解析渲染plotly格式的绘图结果
修正后的完整代码如下:
library(shiny) library(TSstudio) library(forecast) library(plotly) # 定义UI ui <- fluidPage( plotlyOutput("out") ) # 服务端逻辑 server <- function(input, output) { output$out <- renderPlotly({ USgas_split <- ts_split(USgas, sample.out = 12) train <- USgas_split$train test <- USgas_split$test md1 <- auto.arima(train) fc1 <- forecast(md1, h = 12) test_forecast(forecast.obj = fc1, actual = USgas, test = test) }) } shinyApp(ui = ui, server = server)
如果确实需要输出静态图,不需要交互功能,也可以保留原渲染组件,给test_forecast添加use.ggplot = TRUE参数,调用方式改为test_forecast(forecast.obj = fc1, actual = USgas, test = test, use.ggplot = TRUE),即可返回ggplot静态绘图对象适配原渲染逻辑。
内容的提问来源于stack exchange,提问作者汪燕敏
相关产品推荐
相关产品推荐

