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

Shiny下拉菜单切换ggplot数据源失败问题求助

解决Shiny中ggplot切换DataFrame时图表无法渲染的问题

错误原因分析

  1. 反应式对象调用错误:反应式对象df在ggplot中直接以df传入,而反应式对象必须通过df()调用才能获取其返回值,否则ggplot会将其视为函数,触发data不能是函数的报错。
  2. get()参数错误:原代码中get(input)传入的是整个输入对象,应该明确指定获取下拉菜单的选中值input$TEAM。
  3. UI选项参数冗余:selectInput中的c(teams)属于冗余写法,直接传入teams向量即可。

修正步骤

1. 修正反应式数据获取逻辑

将服务器端的df反应式对象修改为:

df <- reactive({
  # 获取选中球队对应的数据集
  get(input$TEAM)
})

更安全的替代方案:提前将所有球队数据存入一个命名列表,通过索引获取(避免get()带来的全局环境变量风险):

# 假设已定义team_data_list,键为球队名,值为对应DataFrame
df <- reactive({
  team_data_list[[input$TEAM]]
})

2. 修正ggplot调用反应式对象的方式

在renderPlot中调用反应式对象时必须加括号:

output$GINI_plot <- renderPlot({
  ggplot(data = df(), aes(CUMSUM, CUMperpts)) + 
    geom_abline(intercept = 0, slope = 1)
})

3. 修正UI下拉菜单选项

去掉selectInput中多余的c():

selectInput("TEAM","TEAM:", teams)

完整修正代码

library(shiny)
library(shinydashboard)
library(ggplot2)

# 假设此处已定义teams向量和对应球队数据集(或team_data_list列表)
# 示例:
# teams <- c("TeamA", "TeamB")
# TeamA <- data.frame(CUMSUM = 1:10, CUMperpts = seq(0,1,length.out=10))
# TeamB <- data.frame(CUMSUM = 1:10, CUMperpts = seq(0,1.2,length.out=10))

ui <- dashboardPage(
  dashboardHeader(title = "NCAA - Lorenz"),
  dashboardSidebar(
    sidebarMenu(
      menuItem("teams", tabName = "teams"),
      menuItem("Correlation", tabName = "Correlation"))),
  dashboardBody(
    tabItems(
      tabItem("teams", 
              box(plotOutput("GINI_plot"), width = 4),
              box(
                selectInput("TEAM","TEAM:", teams), width = 4)),
      tabItem("Correlation", 
              box(plotOutput("correlation_plot"), width = 4),
              box(
                selectInput("STATISTIC","STATISTIC:",
                            c("DRtg","Pts","ast")), width = 4))
    )
  )
)

server <- function(input, output){
  
  df <- reactive({
    get(input$TEAM)
    # 若使用列表则替换为:team_data_list[[input$TEAM]]
  })
  
  output$GINI_plot <- renderPlot({
    ggplot(data = df(), aes(CUMSUM,CUMperpts)) + 
      geom_abline(intercept = 0, slope = 1)
  })
  
  output$correlation_plot <- renderPlot({
    plot(schdata[[input$STATISTIC]], schdata$gini, ylab = "Gini Coef.", xlab = input$STATISTIC)
    # 额外修正:xlab改为input$STATISTIC,显示当前选中的统计量名称
  })

}

shinyApp(ui, server)

额外注意事项

  • 确保teams中的每个名称都对应全局环境中存在的DataFrame(或列表中的对应元素),否则get()会报错。
  • 关于jsonlite的警告:是因为代码中存在命名向量转JSON的操作,建议将相关向量转为命名列表,避免未来版本兼容性问题。

内容的提问来源于stack exchange,提问作者Joseph cotton

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 20:41:06