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

R 在闪亮的应用程序中显示ggplot时,如何捕获控制台中出现的ggplot警告并显示在应用程序中?,r,ggplot2,shiny,R,Ggplot2,Shiny,我有一个简单的应用程序,如下所示,它显示一个ggplot。ggplot在控制台中生成一个警告(参见底部的图片)。我想捕获警告,并将其显示在应用程序中的绘图下 这是我的密码: library(shiny) library(ggplot2) ui <- fluidPage( titlePanel("How do i output ggplot warnings? :("), mainPanel( plotOutput("my_plot_that_generates

我有一个简单的应用程序,如下所示,它显示一个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)
库(闪亮)
图书馆(GG2)

ui当您调用
ggplot
时,它会创建一个类型为
ggplot
的对象,据我所知,在内部,直到您调用对象上的
print()
,消息才会生成。有一个类似问题的解释wrt消息,所以有一个阅读

我们可以做的是显式打印
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)
库(闪亮)
图书馆(GG2)

ui您是否尝试过评估包(请参阅:)?基于此,您可能会先将警告保存到变量中,然后在不依赖于绘图输出的任何位置显示它。一个问题似乎是捕获多条消息和警告。例如,如果我的数据中有NAs,则会生成多个警告(对于带有NAs的每列)。。。当前解决方案仅捕获1条警告。此外,geom_smooth警告实际上是一条信息。因此,如果有警告和消息,我只会收到其中一条。有什么想法吗?:)好的,我通过使用一些东西来“解决”它,基本上,我使用了调用处理程序的
,并建立了一个所有消息/警告的列表,但是它很慢。如果这是一个问题,你可以切换到其他图表库,例如
highcharter
动态图
rCharts
Billboard
plotly
或使用
req
need