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

时间:2018-11-29 08:12:36

标签: 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)

我认为潜在的问题与延迟评估有关,并且该事实只有在trycatch之后才真正呈现(以及生成警告)图表。通过将ggplot调用包装在verbatimTextOutput中,我实际上可以得到警告出现在print()中,但是当然该图不会显示。

由于对问题一无所知,我尝试使用force()而不是print()来解决问题,但这没用。

enter image description here

1 个答案:

答案 0 :(得分:7)

当您调用ggplot时,它会创建一个ggplot类型的对象,据我所知,内部不会生成消息,直到您在该对象上调用print()为止。关于消息的类似问题有一个解释,因此请阅读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)

enter image description here