I have a simple app, below, that displays a ggplot. ggplot generates a warning in the console (see picture at bottom). I'd like to capture the warning, and display it in the app, under the plot.
Here's my code:
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)
I assume the underlying problem has to do with lazy evaluation and the fact that the graph doesn't actually get rendered (and the warning generated) until after the trycatch
. I can actually get the warning to appear in the verbatimTextOutput
by wrapping ggplot call in a print()
, but then of course the plot doesn't show up.
In my ignorance of the problem I've tried force()
rather than print()
but it didn't work.