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

Shiny应用开发问题:如何用sliderInput筛选Lap_1的时间区间

我来帮你搞定这个问题!核心是要给数据加上秒数标识,然后根据滑块选择的范围过滤Lap_1的对应行。下面是修改后的完整代码,我会逐一解释关键改动:

install.packages("shiny")
install.packages("ggplot2")
library(shiny)
library(ggplot2)

# 原始数据添加秒数列
AA <- as.data.frame(cbind(c(10,12,11,12,12,11,12,13,11,9,9,12,11,10,12,9,8,7,9,8,7,9,9,8,9,7,9,10,10,10,7,6,7,8,8,7,6,6,7,8,7,6,7,8,8), 
                          c(rep("Lap_1",15),rep("Lap_2",15),rep("Lap_3",15))))
colnames(AA) <- c("Speed","Lap")
AA$Speed <- as.numeric(as.character(AA$Speed))
# 新增秒数列:每圈对应1-15秒
AA$Sec <- rep(1:15, 3)

ui=shinyUI(
  fluidPage(
    titlePanel("Lap Speed Comparison"),
    sidebarLayout(
      sidebarPanel(
        checkboxGroupInput("lap_choose", label = "Choose the laps", choices = c("Lap_1","Lap_2","Lap_3"),
                           selected = c("Lap_1","Lap_2","Lap_3")), # 默认选中所有圈
        sliderInput("secs_1", "Seconds in Lap 1:", min = 1, max = 15, value = c(3,10), step=1) # 修正最小秒数为1
      ),
      mainPanel(
        plotOutput("Comparison"))
    )
  )
)

server=function(input,output){
  # 数据处理:整合滑块筛选逻辑
  data_1=reactive({
    selected_laps <- input$lap_choose
    # 先根据复选框筛选选中的圈
    filtered_data <- AA[AA$Lap %in% selected_laps, ]
    
    # 如果选中了Lap_1,就根据滑块范围过滤对应的秒数
    if ("Lap_1" %in% selected_laps) {
      # 分离非Lap_1数据和符合条件的Lap_1数据,再合并
      non_lap1 <- filtered_data[filtered_data$Lap != "Lap_1", ]
      lap1_filtered <- filtered_data[filtered_data$Lap == "Lap_1" & 
                                       filtered_data$Sec >= input$secs_1[1] & 
                                       filtered_data$Sec <= input$secs_1[2], ]
      filtered_data <- rbind(non_lap1, lap1_filtered)
    }
    
    return(filtered_data)
  })
  
  output$Comparison <- renderPlot({
    ggplot(data=data_1(), aes(Speed, fill = Lap)) +
      stat_density(aes(y = ..density..), position = "identity", color = "black", alpha = 0.8) +
      xlab("Speed") + ylab("Density") + # 修正x轴标签为Speed更准确
      ggtitle("Lap Speed Distribution Comparison") +
      theme(plot.title = element_text(hjust = 0.5,size=24, face="bold"))
  })
}

shinyApp(ui,server)

关键改动说明

  • 添加秒数列:给AA新增Sec列,用rep(1:15, 3)生成每圈对应的1-15秒,这是实现秒数筛选的基础。
  • 修正滑块参数:把sliderInput的min从0改为1,避免无效的0秒选择,贴合实际数据逻辑。
  • 整合筛选逻辑:在data_1的响应式函数中,先根据复选框选中的圈筛选初始数据;如果选中了Lap_1,就拆分数据,保留符合滑块秒数范围的Lap_1行,再和其他圈的数据合并。
  • 细节优化:给复选框设置默认选中所有圈,修正x轴标签为"Speed"(原标签"Distribution"表述不准确),调整标题让图表更直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:03:06