When showing a ggplot in a shiny app, how do I capture the ggplot warning that appears in the console, and display in the app?
When you call ggplot
it creates an object of type ggplot
, as far as my understanding goes, internally, the messages aren't generated till you call print()
on the object. There's an explanation on similar issue wrt messages so have a read Why does ggplot not allow suppressing of messages generated by its geoms?.
What we can do is explicitly print the ggplot
and capture the messages
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)