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

基于T4水平分组甲状腺患者的Shiny绘图报错求助

解决Shiny应用中Plot2的Error[object object]错误

你在基于T4水平子集化甲状腺数据集后,Plot2出现Error[object object]错误,核心问题集中在reactive对象调用方式错误和数据集不匹配上,以下是具体修复方案:

关键错误点与修复

  • Reactive对象调用错误:data1是reactive函数,必须通过data1()调用才能获取实时子集数据,原代码中data1[[x]]的写法无法正确读取数据,需改为data1()[[x]]。
  • Fill变量数据集不匹配:Plot2中fill = TD$ThryroidClass使用了原全量数据集,与x轴的子集数据行数不一致,导致绘图逻辑冲突,需改为fill = data1()$ThryroidClass。
  • SelectInput标签混淆(优化项):T3、TSH对应的selectInput标签都写了"T4 Rate",易造成误解,建议改为对应变量名(如"T3 Rate"、"TSH Rate")。
  • 触发逻辑优化(可选):若希望切换T4分组时Plot2自动更新,可将input$T4加入x_var的触发条件,避免仅靠按钮更新:
    x_var <- eventReactive(c(input$goButton, input$T4), {
      input$xaxis
    })
    

修复后的完整代码

TD <- thyroid

library(readxl)
library(shiny)
library(ggplot2)
library(shinythemes)
library(DT)

ui <- shinyUI(fluidPage(pageWithSidebar(
  headerPanel("Test App"),
  sidebarPanel(
    selectInput("xaxis", "Choose a x variable", choices = names(TD)),
    selectInput("T4", "T4 Rate", choices = c("All","0 - 80","80 - 140","> 140")),
    selectInput("T3", "T3 Rate", choices = c("All","0 - 80","80 - 140","> 140")),
    selectInput("TSH", "TSH Rate", choices = c("All","0 - 80","80 - 140","> 140")),
    
    actionButton("goButton","Update")
  ),
  mainPanel(
    tabsetPanel(
      tabPanel('Plot1', plotOutput("plot1")),
      tabPanel('Plot2', plotOutput("plot2"))
    ))
)
))

server <- shinyServer(function(input,output, session){
  
  data1 <- reactive({
    if(input$T4 == "All"){
      TD
    }
    else if(input$T4 == "0 - 80"){
      TD[which(TD$T4 >= 0 & TD$T4 < 80),]
    }
    else if(input$T4 == "80 - 140"){
      TD[which(TD$T4 >= 80 & TD$T4 < 140),]
    }
    else{
      TD[which(TD$T4 >= 140),]
    }
  })

  x_var <- eventReactive(input$goButton, {
    input$xaxis
  })
  
  output$plot1 <- renderPlot({
    x <- x_var()
    p <- ggplot() + geom_bar(aes(x=TD[[x]], fill = TD$ThryroidClass))
    p
  })
  
  output$plot2 <- renderPlot({
    x <- x_var()
    subset_data <- data1()
    p <- ggplot(subset_data) + geom_bar(aes(x=.data[[x]], fill = ThryroidClass))
    p
  })
})

shinyApp(ui,server)

额外说明

修复后的Plot2先将reactive对象赋值给subset_data,再传入ggplot,代码可读性更强;同时使用.data[[x]]的方式引用变量,符合ggplot的规范。另外需注意ThryroidClass字段名是否拼写正确(比如是否应为ThyroidClass),拼写错误也会导致绘图失败。

内容的提问来源于stack exchange,提问作者souhail Lyamani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 06:41:33