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

如何在Shiny的ggplot中根据所选赛事动态更改副标题为热门队名称

Fixing the Dynamic Subtitle to Show Favorite Team Name

I see you want to swap that fixed "Game Spead" subtitle with the favorite team name for the selected event—let's get that sorted out! Here's the adjusted code with clear explanations of the key changes:

server = function(input, output, session) {
  # Load data
  df3 = read.csv(paste0("C:/Users/Ethan Altmayer/Desktop/Gambling Data/R Analysis/Consolidated_Data_", Sys.Date()-1, ".csv"))
  
  # Summarize data
  data = reactive({
    req(input$Event)
    # Filter to only favorite teams, then narrow to selected event
    df3 %>% 
      filter(Side == "Favorite", Event %in% input$Event)
  })
  
  # Update event select input dynamically (added unique() to avoid duplicate choices)
  observe({
    updateSelectInput(session, "Event", choices = unique(df3$Event))
  })
  
  # Plot with dynamic subtitle
  output$plot = renderPlot({
    plot_data <- data()
    # Extract the favorite team name (adjust column name if your data uses something like 'Team_Name')
    favorite_team <- unique(plot_data$Team)
    
    ggplot(plot_data, aes(x = Time.Remaining)) +
      geom_line(size = 1, aes(y = Original.Line, color = "Original Line")) +
      geom_point(color = "orchid", size = 2, aes(y = Live.Line)) +
      geom_line(size = 1, aes(y = Live.Line, color = "Live Line")) +
      labs(
        title = "Live Line vs Original",
        subtitle = paste("Favorite Team:", favorite_team),  # Dynamic subtitle here
        y = "Line", 
        x = "Time Remaining"
      ) +
      facet_wrap(~ Half) +
      scale_x_reverse() +
      scale_color_manual(
        name = "Line Type", 
        values = c("Original Line" = "#69b3a2", "Live Line" = "steelblue")
      ) +
      theme(plot.background = element_rect(fill = "Snow"))
  })
}

ui = basicPage(
  h1("Game Line Tracker"),
  selectInput(inputId = "Event", label = "Choose Game", choices = "Names"),
  plotOutput("plot")
)

shinyApp(ui = ui, server = server)

Key Changes Made:

  • Dynamic Subtitle: We first store the reactive dataset in plot_data, then pull the unique favorite team name using unique(plot_data$Team) (swap Team with your actual column name if it's different, like Favorite_Team). The subtitle is built with paste() to display this team name dynamically based on the selected event.
  • Cleaner Color Mapping: Switched from raw color strings in aes() to meaningful labels, then mapped them to your desired colors with scale_color_manual()—this avoids unexpected legend mismatches and makes the code easier to read.
  • Unique Event Options: Added unique() to updateSelectInput to remove duplicate event entries from the dropdown, which makes the app feel more polished for users.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:16:17