在闪亮的应用程序中显示ggplot时,如何捕获控制台中显示的ggplot警告,并显示在应用程序中?

sha*_*ker 15 r ggplot2 shiny

我在下面有一个简单的应用程序,它显示了一个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)
Run Code Online (Sandbox Code Playgroud)

我假设潜在的问题与延迟评估有关,并且事实上图形实际上没有被渲染(并且生成了警告),直到之后trycatch.我实际上可以verbatimTextOutput通过在a中包含ggplot调用来获得警告print(),但当然情节不会显示出来.

在我对这个问题的无知我已经试过force(),而不是print(),但没有奏效.

在此输入图像描述

Por*_*hop 8

当你调用ggplot它时,创建一个类型的对象ggplot,就我的理解而言,在内部,在你调用print()对象之前不会生成消息.有关类似问题的解释wrt消息所以请阅读为什么ggplot不允许抑制其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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 一个问题似乎是捕获多条消息和警告。例如,如果我的数据中有 NA,则会生成多个警告(对于带有 NA 的每一列)...当前解决方案仅捕获 1 个警告。此外, geom_smooth 警告实际上是作为消息出现的。因此,如果有警告 * 和 * 消息,我只会收到其中之一。有任何想法吗?:) (2认同)