【问题标题】:Display blank plot in shiny instead of error以闪亮而不是错误显示空白图
【发布时间】:2015-08-31 04:47:15
【问题描述】:

当我有传递给renderPlot(或其他渲染函数)的反应数据时,数据通常最初是空的,直到发生某些操作。默认渲染通常会在操作发生之前在应用中显示错误,因为数据为空,即

错误“x”必须是数字

在这个例子中。是否有一些标准方法可以让渲染函数在没有数据时起作用(如果出现错误或只是空白则可能不渲染)?我知道我可能会很麻烦地构造所有反应值,这样输出就会是空白的,但这似乎是不必要的工作。

rMarkdown 中的示例闪亮

---
title: "Example"
runtime: shiny
output: html_document
---

```{r}
shinyApp(
    shinyUI(fluidPage(
        inputPanel( 
            numericInput("n", "n", 10),
            actionButton("update", "Update")
        ),
        plotOutput("plot")
    )),

    shinyServer(function(input, output) {
        values <- reactiveValues()
        values$data <- c()

        obs <- observe({
            input$update
            isolate({ values$data <- c(values$data, runif(as.numeric(input$n), -10, 10)) })
        }, suspended=TRUE)

        obs2 <- observe({
            if (input$update > 0) obs$resume()
        })

        output$plot <- renderPlot({
            dat <- values$data
            hist(dat)
        })
    }) 
)
```

【问题讨论】:

标签: r shiny r-markdown


【解决方案1】:

您可以在尝试绘制变量之前使用exists 函数查看变量是否存在,否则可以根据需要进行更改:

renderPlot({
    if(exists("values$data")) {
      dat <- values$data 
    } else {
      dat <- 0
    }
    hist(dat)
})

【讨论】:

  • 谢谢,但我正在寻找一种避免制衡的方法。只是一种让默认渲染返回空白而不是错误的方法。
  • 这将取决于您的实际绘图方法 - 大多数 R 图表不会为您提供空白绘图。 ggplot2 图形可能使用 geom_blank 或空的 data.frame。对于您上面的示例,我会将 values$data
【解决方案2】:

尝试围绕tryCatch 中可能出错的行。在你的例子中,hist(dat) 是什么错误,所以像这样包围它:

tryCatch(
  { hist(dat) }, # Code that might error goes here, between the { }
  error = function(e) {""} # Leave this line as-is.
)

这说明了闪亮:

  • 尝试运行hist(dat),然后
  • 如果您无法在没有错误的情况下运行它,只需显示一个空字符串即可。

现在没有更多错误消息,您的直方图仍按预期工作。

工作示例

这是您实施了tryCatch 解决方案的MRE - 向下滚动到评论中提到# CHANGES HERE 的位置;它只是用 4 个 tryCatch() 行替换了 hist(dat) - 这是唯一的变化。

---
title: "Example"
runtime: shiny
output: html_document
---

```{r}
shinyApp(
    shinyUI(fluidPage(
        inputPanel( 
            numericInput("n", "n", 10),
            actionButton("update", "Update")
        ),
        plotOutput("plot")
    )),

    shinyServer(function(input, output) {
      

        values <- reactiveValues()
        values$data <- c()

        obs <- observe({
            input$update
            isolate({ values$data <- c(values$data, runif(as.numeric(input$n), -10, 10)) })
        }, suspended=TRUE)

        obs2 <- observe({
            if (input$update > 0) obs$resume()
        })

        output$plot <- renderPlot({
            dat <- values$data
            # CHANGES HERE (NEXT 4 LINES)
            tryCatch(
              { hist(dat) }, 
              error = function(e) {""} 
              )
        })
    }) 
)
```

【讨论】:

    猜你喜欢
    • 2021-09-23
    • 2012-03-24
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 2020-04-21
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多