gpt4 book ai didi

r - 在 Shiny 的应用程序中显示 ggplot 时,如何捕获控制台中出现的 ggplot 警告并显示在应用程序中?

转载 作者:行者123 更新时间:2023-12-03 20:53:07 26 4
gpt4 key购买 nike

我在下面有一个简单的应用程序,它显示了一个 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 之后,图形才真正被渲染(并生成警告)。 .我实际上可以让警告出现在 verbatimTextOutput通过将 ggplot 调用包装在 print() 中,但随后情节当然不会出现。

在我对问题的无知中,我尝试了 force()而不是 print()但它没有用。

enter image description here

最佳答案

当您调用 ggplot它创建了一个 ggplot 类型的对象,据我了解,在内部,直到您调用 print() 才会生成消息物体上。有关于类似问题 wrt 消息的解释,请阅读 Why does ggplot not allow suppressing of messages generated by its 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)

enter image description here

关于r - 在 Shiny 的应用程序中显示 ggplot 时,如何捕获控制台中出现的 ggplot 警告并显示在应用程序中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53534449/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com