R Shiny中filter函数失效致图表与表格无法正常显示问题
NFL Draft EPA热力图应用修复方案
问题根源
你的热力图无内容、过滤表格为空的核心原因是过滤器的选项值与数据中的字段值完全不匹配:
- 赛季过滤器:你把年份标签(如"2004")映射成了数字1,但数据里的
season.y是实际年份数值(2004),两者无法匹配; - 位置过滤器:你把位置标签(如"QB")映射成了数字1,但数据里的
position.x是字符型的位置缩写,同样无法匹配。
修复步骤
调整两个checkboxGroupInput的choices参数,让选项值与数据中的实际字段值保持一致:
- 赛季选项的値直接使用对应年份的数值;
- 位置选项的値直接使用对应位置的缩写字符。
修正后的完整代码
library(shiny) library(ggplot2) library(dplyr) ui = fluidPage( titlePanel('NFL Draft'), sidebarLayout( sidebarPanel( checkboxGroupInput('seasons', 'Seasons:', choices = c('2004' = 2004, '2005' = 2005, '2006' = 2006, '2007' = 2007, '2008' = 2008, '2009' = 2009, '2010' = 2010, '2011' = 2011, '2012' = 2012, '2013' = 2013, '2014' = 2014, '2015' = 2015, '2016' = 2016), selected = c(2004,2005,2006,2007,2008)), checkboxGroupInput('positions', 'Positions:', choices = c('QB' = 'QB', 'TE' = 'TE', 'WR' = 'WR', 'RB' = 'RB', 'FB' = 'FB'), selected = 'QB')), mainPanel( plotOutput('epa_by_draft'), tableOutput('table') ) ) ) server <- function(input, output) { position.x = c('QB', 'QB', 'QB', 'RB', 'RB', 'WR', 'WR', 'TE', 'FB', 'FB', 'WR', 'TE', 'TE', 'QB', 'QB') season.y = c(2012, 2010, 2004, 2004, 2010, 2005, 2007, 2006, 2008, 2009, 2011, 2014, 2013, 2015, 2016) round = c(1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 1) total_epa = c(-3, -2, -1, 0, 1, 2, 3, -3, -2, -1, 0, 1, 2, 3, 0) draft_epa = data.frame(position.x, season.y, round, total_epa) filtered_draft_epa = reactive({ draft_epa %>% filter(position.x %in% input$positions & season.y %in% input$seasons) }) output$table = renderTable({ filtered_draft_epa() }) output$epa_by_draft = renderPlot({ ggplot(filtered_draft_epa(), aes(x = season.y, y = round, fill = total_epa)) + geom_tile() + scale_fill_gradient(high = 'green', low = 'red', limits = c(-3, 3)) }) } shinyApp(ui = ui, server = server)
额外优化点
- 移除了
renderTable里的print()函数,renderTable直接接收数据框即可; - 简化了
scale_fill_gradient的limits参数,因为已知范围是-3到3,无需用floor和ceiling。
内容的提问来源于stack exchange,提问作者jordanar189
相关产品推荐
相关产品推荐

