[英]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?
我在下面有一个简单的应用程序,它显示了一个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
。 我实际上可以通过在print()
包装ggplot调用来获得出现在verbatimTextOutput
的警告,但当然情节不会显示出来。
在我对问题的无知中,我尝试了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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.