You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny应用中shinyjs与ggplot2::autoplot共存报错的解决方案问询

Fixing "Error in unclass(x) : cannot unclass an environment" When Using shinyjs with ggfortify::autoplot in Shiny

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:13:45