在R Shiny中创建空的dygraph

问题描述 投票:1回答:1

我正在使用Dygraphs包来实现R闪亮的实际和时间序列预测值的可视化。这是我用来生成Dygraph的示例代码。在某些情况下,数据点较少Holt Winters(gamma = T)没有给出任何预测,我需要显示标题为“数据不足”的空Dygraph。我无法做到这一点。感谢任何帮助

library(dygraphs)

plotDyg <- fluidPage(
  fluidRow(
    box(selectizeInput("c1", "Enter a key",
                         choices = reactive({sort(unique(df$key))})(),
                         multiple = FALSE),width=3),
    box(dygraphOutput("tsDy"), width = 10, height = 500))
)

ui <- dashboardPage(
  dashboardHeader(title = "XYZ"),
  dashboardSidebar(
    sidebarMenu(
      menuItem("abc", tabName = "sidebar2", icon = icon("bar-chart") ,
               menuSubItem("def",icon = icon("folder-open"), tabName = "subMenu1")
               )
      )
  ),
  dashboardBody(
    tabItems(
      tabItem(tabName = "subMenu1", 
              fluidRow(
                tabBox(
                  title = "ghi", id = "tabset2",height = "1500px",width = 100,
                  tabPanel("abcdef", plotDyg)
                )
              )
      )

    )

  )
)

 server <- function(input, output) {
  output$tsDy <- renderDygraph({
    if(!is.null(input$c1)){
      df.0 <- reactive({df[df$key == input$c1,]})()
      tspred <- reactive({
                df.0 <- convert_to_ts(df.0)  # converts column "fin_var" to a monthly time series and returns the entire dataframe
                act <- df.0$fin_var
                hw <- tryCatch(HoltWinters(df.0$fin_var), error=function(e)NA)
                if(length(hw) > 1){
                  p <- predict(hw, n.ahead = 12, prediction.interval = TRUE, level = 0.95)
                  all1 <- cbind(act, p)
                }else{all1 <- matrix()}
         })
         if(!is.na(tspred())){
           dygraph(tspred(), main = "TS Predictions") %>%
           dySeries("act", label = "Actual") %>%
           dySeries(c("p.lwr", "p.fit", "p.upr"), label = "Predicted") %>%
           dyOptions(drawGrid = F) %>%
           dyRangeSelector()
         }else{dygraph(matrix(0), main = "Insufficient Data")} # I could just do 'return()' but I want to show an empty Dygraph with the title
    }else{return()}
  })
}
r shiny dygraphs shinyjs
1个回答
1
投票

我也无法使用空的时间序列渲染Dygraphs。为了向用户呈现消息,我使用了validate/need functions in Shiny

在你的情况下,我会替换

 if(!is.na(tspred())){

 validate(need(!is.na(tspred())), "Insufficient Data"))

这将避免Dygraphs中的“错误:参数长度为零”消息,并向最终用户打印适当的消息。

© www.soinside.com 2019 - 2024. All rights reserved.