如何在Shiny中基于下拉框从DataFrame生成直方图并运用选择值
解决Shiny应用下拉选择、数据匹配与直方图生成问题
关键修正点
- 确保下拉选项与原始数据匹配:直接从薪资数据集
data中提取唯一选项,替代手动创建的wxdata,从根源避免选项不匹配问题 - 实时获取选择结果:Shiny的
input$RemoteWork和input$CompanySize会实时同步用户的下拉选择,无需额外保存按钮 - 基于选择生成直方图:在
server中根据选择过滤数据,用ggplot2绘制薪资分布直方图
修改后的完整代码
library(dplyr) library(ggplot2) library(shiny) # 读取原始数据 data <- read.csv("C:/Users/lewis/OneDrive/Desktop/STA 580( R programming)/Final_Project/salaries_entry.csv") # 直接从原始数据提取下拉选项(假设数据中有Remote和Size列,可根据实际列名调整) remotelist <- unique(data$Remote) sizelist <- unique(data$Size) # 移除空值选项(如果有的话) remotelist <- remotelist[!is.na(remotelist)] sizelist <- sizelist[!is.na(sizelist)] ui <- fluidPage( titlePanel("Data Science / Data Engineer Salaries"), sidebarLayout( sidebarPanel( inputPanel( selectInput( "RemoteWork", label = "Select Amount of Remote Work", choices = remotelist ) ), inputPanel( selectInput( "CompanySize", label = "Select the Size of the Company", choices = sizelist ) ) ), mainPanel( h4("The purpose of this app is to give you an idea"), h4("about the potential money you could be making as an"), h4("entry level employee in the Data Science field based "), h4("on a few key factors. Test it out and Get that BAG!"), # 添加直方图输出区域 plotOutput("salaryHist") ) ) ) server <- function(input, output) { # 基于用户选择过滤数据,生成反应式数据集 filtered_data <- reactive({ data %>% filter(Remote == input$RemoteWork, Size == input$CompanySize) }) # 绘制薪资直方图 output$salaryHist <- renderPlot({ filtered <- filtered_data() # 处理过滤后无数据的情况 if(nrow(filtered) == 0) { ggplot() + annotate("text", x = 1, y = 1, label = "No data matches your selection", size = 5) + theme_void() } else { ggplot(filtered, aes(x = salary)) + # 假设薪资列名为salary,根据实际调整 geom_histogram(bins = 15, fill = "#2E8B57", color = "white") + labs(title = "Salary Distribution", x = "Salary", y = "Count") + theme_minimal() } }) } shinyApp(ui = ui, server = server)
重要说明
- 列名适配:代码中假设原始数据的远程工作列名为
Remote、公司规模列名为Size、薪资列名为salary,请根据你的salaries_entry.csv实际列名修改 - 实时响应:用户调整下拉选择时,
filtered_data会自动重新过滤数据,直方图实时更新 - 空数据处理:如果选择组合没有对应数据,会显示提示文本,避免报错
- 选项验证:因为下拉选项直接从原始数据提取,用户选择的内容必然存在于DataFrame中,无需额外验证逻辑
内容的提问来源于stack exchange,提问作者Tyler Lewis
相关产品推荐
相关产品推荐

