我在下面有一个简单的应用程序,它显示了一个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(),但没有奏效.
当你调用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)