Shiny应用中shinyjs与ggplot2::autoplot共存报错的解决方案问询
I’ve run into this exact conflict between shinyjs and ggfortify’s autoplot function before, so I know exactly what’s causing the issue. The error pops up because shinyjs injects small environment modifications that interfere with how ggfortify parses the linear model (lm) object when generating diagnostic plots.
Here are two reliable fixes that let you keep using both packages without issues:
Fix 1: Explicitly print the ggplot object in renderPlot
Shiny’s renderPlot handles most ggplot objects smoothly, but ggfortify generates a multi-panel plot that sometimes needs an explicit print() call to render correctly when shinyjs is active. Update your renderPlot block like this:
output$autoplot <- renderPlot({ req(rv_autoplot()) print(rv_autoplot()) # Add print() to force proper rendering })
Fix 2: Isolate model and plot generation in a local environment
Wrapping your model creation and autoplot call inside a local() block creates a clean, isolated environment that doesn’t pick up the modifications from shinyjs. Adjust your eventReactive code:
rv_autoplot <- eventReactive(input$run, { local({ data <- iris a <- lm(data = data, Sepal.Length ~ Petal.Length) p <- autoplot(a, which = 1:6, label.size = 2, data = data) return(p) }) })
Full Working Code (with Fix 1 applied)
Here’s your complete code with shinyjs enabled and the fix in place:
library(shiny) library(ggplot2) library(ggfortify) library(shinyjs) # Uncommented ui <- fluidPage( useShinyjs(), # Uncommented div( actionButton("run", "Run"), uiOutput("ui_autoplot") ) ) server <- function(input, output, session) { data <- iris rv_autoplot <- eventReactive(input$run, { a <- lm(data = data, Sepal.Length ~ Petal.Length) p <- autoplot(a, which = 1:6, label.size = 2, data = data) return(p) }) output$autoplot <- renderPlot({ req(rv_autoplot()) print(rv_autoplot()) # Added print() }) output$ui_autoplot <- renderUI({ plotOutput("autoplot") }) } shinyApp(ui = ui, server = server)
If you’re able to upgrade your R version and packages (your current setup is a bit outdated), that might also resolve the issue permanently. But the fixes above work perfectly with your existing environment.
内容的提问来源于stack exchange,提问作者qfazille

