Home > database >  How to Error Handle the reative in R shiny when there is no data
How to Error Handle the reative in R shiny when there is no data

Time:10-14

I want to make an error handling that when there is data then shows the plotly chart and when the data is null, then just show a white chart not showing up the error at the UI. Here is the code that I extracted from my original code. After running the app.R, the error will occurs on the UI when data is null.

I have also used try catch function try to remove the error but failed. Any suggestions will be really appreciate.

# Define UI for app that draws a histogram ----
library(ggplot2)
library(stringr)
ui <- fluidPage(
  
  # App title ----
  titlePanel("Hello Shiny!"),
    # Main panel for displaying outputs ----
    mainPanel(
      
      # Output: Histogram ----
      plotlyOutput("toolbar")
      
    )
  )

server <- function(input, output) {
  data == data.frame()
  if (!is.na(data)){
    print("no tool_install info!!")
    proc_bars <- reactiveValues(plot = NULL)
    print(proc_bars)
    output$toolbar <- renderPlotly({
      tryCatch(
        expr = {print(plotly::ggplotly(proc_bars$plot))},
        error = function(e){""}
      )
    })
    
  }}

shinyApp(ui, server)

CodePudding user response:

Perhaps you can adapt this to your use case.

library(ggplot2)
library(stringr)
library(plotly)

NoDataPlotly <- function(){
  df <- data.frame()
  p <- ggplot(df)   geom_point()   xlim(0, 10)   ylim(0, 10)   
    annotate("text", x=3.9, y=5.0, size=40, col="red", label="(" )  
    annotate("text", x=5, y=5.6, size=12, col="red", label="o  o" )  
    annotate("text", x=6.1, y=5.0, size=40, col="red", label=")" )  
    annotate("text", x=5, y=5.1, size=12, col="red", label="|" )  
    geom_segment(aes(x = 4.7, xend = 5.3, y = 4.4, yend = 4.4), size=2, color="red")  
    annotate("text", x=5, y=3, size=6, col="red", label="No Data") 
  
  bp <- ggplotly(p)
  bp
}

ui <- fluidPage(
  
  # App title ----
  titlePanel("Hello Shiny!"),
  # Main panel for displaying outputs ----
  mainPanel(
    actionButton('dfrdf','Alternate'),
    # Output: Histogram ----
    plotlyOutput("toolbar")
    
  )
)

server <- function(input, output) {
  rv <- reactiveValues(plot=NULL)
  df1 <- data.frame(x=c(3,4,5),y=c(15,12,5))
  p <- ggplot(df1, aes(x=x,y=y))   geom_col()
  
  ###  This is just an actionbutton to imitate your data being NULL in some instances
  observeEvent(input$dfrdf,{
    k <- as.numeric(input$dfrdf) %% 2
    if (k==0){
      rv$plot <- ggplotly(p)
    }else rv$plot <- NoDataPlotly()  ###  assign a dummy plot when data is NULL
  },ignoreNULL = FALSE)
  
  output$toolbar <- renderPlotly({
    dev.off()
    rv$plot
  })
 
}

shinyApp(ui, server)

output

  • Related