【发布时间】:2019-05-01 05:54:58
【问题描述】:
我有一个简单的应用程序,如下所示,它显示了一个 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 调用包装在 print() 中来让警告出现在 verbatimTextOutput 中,但是当然情节不会出现。
在我不知道问题的情况下,我尝试了force() 而不是print(),但没有奏效。
【问题讨论】:
-
你试过评估包吗(见:cran.r-project.org/web/packages/evaluate/index.html)?基于stackoverflow.com/a/4963132/8757228,您可以先将警告保存到变量中,然后在您想要的任何位置显示它,而与绘图输出无关。