【问题标题】:When showing a ggplot in a shiny app, how do I capture the ggplot warning that appears in the console, and display in the app?在闪亮的应用程序中显示 ggplot 时,如何捕获控制台中出现的 ggplot 警告并显示在应用程序中?
【发布时间】:2019-05-01 05:54:58
【问题描述】:

我有一个简单的应用程序,如下所示,它显示了一个 ggplot。 ggplot 在控制台中生成警告(见底部图片)。我想捕获警告,并将其显示在应用程序的绘图下方。

这是我的代码:

library(shiny)
library(ggplot2)

ui <- fluidPage(

   titlePanel("How do i output ggplot warnings? :("),
   mainPanel(
       plotOutput("my_plot_that_generates_warnings"),
       tags$br(),
       verbatimTextOutput(outputId='ggplot_warnings')
   )
)

server <- function(input, output) {

    messages <- reactiveValues(ggplot_warning = 'How to capture warning and display it?')
    output$my_plot_that_generates_warnings <- renderPlot({
        tryCatch({

            ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) +
                geom_point() +
                geom_smooth()

        }, message = function(e) {
            messages$ggplot_warning <- e$message
        }, warning = function(e) {
            messages$ggplot_warning <- e$message
        }, error = function(e) {
            messages$ggplot_warning <- e$message
        })
    })

    output$ggplot_warnings <- renderPrint({
        cat(messages$ggplot_warning)
    })
}

shinyApp(ui = ui, server = server)

我认为根本问题与惰性求值有关,并且直到trycatch 之后,图形才真正被渲染(并生成警告)。实际上,我可以通过将 ggplot 调用包装在 print() 中来让警告出现在 verbatimTextOutput 中,但是当然情节不会出现。

在我不知道问题的情况下,我尝试了force() 而不是print(),但没有奏效。

【问题讨论】:

标签: r ggplot2 shiny


【解决方案1】:

当您调用ggplot 时,它会创建一个ggplot 类型的对象,据我所知,在内部,直到您在该对象上调用print() 才会生成消息。有关于类似问题 wrt 消息的解释,请阅读Why does ggplot not allow suppressing of messages generated by its geoms?

我们可以做的是显式打印ggplot 并捕获消息

library(shiny)
library(ggplot2)

ui <- fluidPage(

  titlePanel("This is now fixed :)"),
  mainPanel(
    plotOutput("my_plot_that_generates_warnings"),
    tags$br(),
    verbatimTextOutput(outputId='ggplot_warnings')
  )
)

server <- function(input, output) {

  data <- reactive({
    ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) +
      geom_point() +
      geom_smooth()
  })

  dataerrors <- reactive({
    tryCatch({
      print(data())
    }, message = function(e) {
      return(e$message)
    }, warning = function(e) {
      return(e$message)
    }, error = function(e) {
      return(e$message)
    })
  })

  output$my_plot_that_generates_warnings <- renderPlot({
    data()
  })

  output$ggplot_warnings <- renderPrint({
    dataerrors()
  })
}

shinyApp(ui = ui, server = server)

【讨论】:

  • 一个问题似乎是捕获多个消息和警告。例如,如果我的数据中有 NA,则会生成多个警告(对于具有 NA 的每一列)...当前解决方案仅捕获 1 个警告。此外,geom_smooth 警告实际上是作为消息出现的。因此,如果有警告 消息,我只会收到其中一个。有任何想法吗? :)
  • 好吧,我基本上通过使用adv-r.hadley.nz/conditions.html 的一些东西“解决”了它,我使用withCallingHandlers 并建立了所有消息/警告的列表,但它是sloooowwwww。
  • 如果这是一个问题,您可以切换到其他图表库,例如highcharterdygraphsrChartsbillboarderplotly 或编写自己的错误处理reqneed
猜你喜欢
  • 2016-10-15
  • 2016-12-20
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 2017-11-18
  • 2018-09-07
相关资源
最近更新 更多