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

Shiny中基于选定类别动态子集化数据并绘图的实现咨询

Solution for Dynamic Data Subsetting in Shiny

Got it, let's get your Shiny app to dynamically filter data based on the selected year (and scale easily for more variables later!). Here's how to fix your code step by step:

Key Issues in Your Current Code

  • You're using the full df dataset directly in the plot, so no filtering happens when the year selection changes.
  • The aes_string(df$PlayLocation, ...) syntax is unnecessary and can cause issues—better to reference column names directly once you have your filtered data.

Fixed Code Implementation

First, I'll assume your df has a column named Year that matches the values in your selectInput (e.g., "2013", "2014", etc.). Here's the updated code:

library(shiny)
library(ggplot2)

# Assuming your df is defined somewhere above this (e.g., loaded from a CSV)
# df <- read.csv("your_data.csv")

ui = dashboardPage(
  dashboardHeader(title = "NFL"),
  dashboardSidebar(
    sidebarMenu(
      selectInput(
        "Year",
        label = "Year",
        choices = c("2013" = "2013", "2014" = "2014", "2015" = "2015", "2016"= "2016"),
        selected="2013"
      )
    )
  ),
  dashboardBody(
    fluidRow(
      plotOutput(outputId = "p1"),
      width = 150
    )
  )
)

server=function(input,output) {
  # Create a reactive filtered dataset
  filtered_data <- reactive({
    # Filter df to only rows where Year matches the selected input
    # Using base R:
    df[df$Year == input$Year, ]
    
    # If you use dplyr, this is cleaner (uncomment if you have dplyr installed):
    # df %>% filter(Year == input$Year)
  })
  
  output$p1 = renderPlot({
    # Use the reactive filtered_data() (note the parentheses!)
    ggplot(data = filtered_data(), aes(x = PlayLocation, y = YardageResult, color = PlayLocation)) +
      geom_point() +
      geom_jitter() +
      labs(x = "Play Location", y = "Yards Gained") +
      theme(legend.position = "none")
  })
}

shinyApp(ui=ui, server=server)

What's Changed & Why

  1. Reactive Filtered Data: The filtered_data reactive object automatically updates every time input$Year changes. It subsets your original df to only include rows where the Year column matches the selected value. This works for both string and factor values (since we're using == to match directly).
  2. Plot Uses Reactive Data: In renderPlot, we call filtered_data() (with parentheses) to get the latest filtered dataset. This ensures the plot always reflects the current selection.
  3. Cleaner Aesthetics: We removed aes_string and df$ references—since we're using the filtered dataset, we can just use the column names directly in aes().

Scaling to More Variables

When you add more subsetting variables (like a team selectInput or position filter), just update the reactive filter:

filtered_data <- reactive({
  df[df$Year == input$Year & df$Team == input$Team, ]
  # Or with dplyr:
  # df %>% filter(Year == input$Year, Team == input$Team)
})

This pattern works for any number of categorical filters—just add more conditions to the subsetting logic!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:03:16