【问题标题】:How to Error Handle the reative in R shiny when there is no data没有数据时如何错误处理R闪亮中的反应
【发布时间】:2021-12-02 09:43:32
【问题描述】:

我想做一个错误处理,当有数据时显示绘图图表,当数据为空时,只显示一个白色图表,而不是在 UI 上显示错误。这是我从原始代码中提取的代码。运行app.R后,数据为null时UI会报错。

我也使用了try catch函数尝试删除错误但失败了。任何建议将不胜感激。

# 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)

【问题讨论】:

    标签: r shiny reactive


    【解决方案1】:

    也许您可以根据您的用例进行调整。

    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)
    

    【讨论】:

      猜你喜欢
      • 2014-05-27
      • 2017-07-06
      • 1970-01-01
      • 2012-11-14
      • 1970-01-01
      • 2018-08-01
      • 2013-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多