如何在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 usingunique(plot_data$Team)(swapTeamwith your actual column name if it's different, likeFavorite_Team). The subtitle is built withpaste()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 withscale_color_manual()—this avoids unexpected legend mismatches and makes the code easier to read. - Unique Event Options: Added
unique()toupdateSelectInputto remove duplicate event entries from the dropdown, which makes the app feel more polished for users.
内容的提问来源于stack exchange,提问作者alty1723
相关产品推荐
相关产品推荐

