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

Shiny ggplot图表响应式数据处理及专业成绩折线图实现问题

修正后的Shiny交互可视化实现

先直接给出可运行的完整代码:

library(shiny)
library(ggplot2)
library(dplyr)

# 原始数据集
df = data.frame(
  Year = c('2015', '2015', '2015', '2016', '2016', '2016', '2017', '2017', '2017'),
  Major = rep(c('Economics', 'Architecture', 'Psychology'), times = 3),
  Grade = c(5,4,4,4,5,4,5,5,4))

ui <- fluidPage(
  # 专业选择下拉框:去重选项,统一inputId为Major
  selectInput(inputId = "Major", label = "选择专业", choices = unique(df$Major)),
  plotOutput("gradePlot")
)

server <- function(input, output, session){
  
  # 创建响应式过滤数据集:避免命名冲突,用filtered_df代替df
  filtered_df <- reactive({
    df %>% 
      dplyr::filter(Major == input$Major) %>%
      # 将Year转为数值型,让折线图的x轴顺序更合理
      mutate(Year = as.numeric(Year))
  })
  
  output$gradePlot = renderPlot({
    ggplot(data = filtered_df(), aes(x = Year, y = Grade, group = Major, color = Major)) +
      geom_line(linewidth = 1) +
      geom_point(size = 3) + # 添加数据点更清晰
      labs(title = "各专业年度成绩变化", x = "年份", y = "成绩") +
      theme_minimal()
  })
}

shinyApp(ui, server)

关键修改说明

  • UI部分修正:

    • 移除了fluidPage中多余的inputId = 'MajorSelect'参数,该参数不属于fluidPage的合法参数。
    • 给selectInput的choices使用unique(df$Major),避免下拉框出现重复的专业选项。
    • 把plotOutput的id改为gradePlot,语义更清晰,避免和变量名混淆。
  • Server部分修正:

    • 响应式数据集命名为filtered_df,避免和原始数据集df重名导致的覆盖问题。
    • 过滤条件里使用input$Major,和selectInput的inputId保持一致(原代码里inputId是"Major"却用了input$MajorSelect,完全不匹配)。
    • 将Year转为数值型,确保折线图的x轴按年份顺序排列(原数据中Year是字符型,ggplot会按字符顺序处理,这里虽然顺序对,但转为数值型更严谨)。
    • 给折线图添加了数据点和美化样式,提升可视化效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 06:25:23