user1946217
user1946217

Reputation: 1753

create empty dygraph in Rshiny

I'm using Dygraphs package for visualizing actual and the time series predicted values in R shiny. Here is the sample code that I used to generate the Dygraph. In some cases where the data points are less Holt Winters(gamma =T) does not give any prediction and I need to show an empty Dygraph with the title "Insufficient Data"). I'm not able to do this. Appreciate any help on this

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()}
  })
}

Upvotes: 1

Views: 570

Answers (1)

Will Etson
Will Etson

Reputation: 71

I too am unable to render Dygraphs with an empty time series. To render a message to the user I used the validate/need functions in Shiny

In your case I would replace

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

With

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

This will avoid the "error: argument is of length zero" message within Dygraphs and print an appropriate message to the end user.

Upvotes: 2

Related Questions