如何在R/Shiny中使用开关控件切换显示指定图表
解决R Shiny应用功能需求问题
以下是实现你需求的完整修改代码,核心调整包括修复开关输入ID拼写错误、添加滑块禁用逻辑、重构图表渲染逻辑:
library("shiny") library("shinyWidgets") library("gapminder") library(tidyverse) library(highcharter) # 预加载数据(复用已定义的数据集) hc_data_1 <- gapminder %>% filter(country == 'Chile') hc_data_2 <- gapminder %>% filter(country == 'Argentina') hc_data_3 <- gapminder %>% filter(country == 'France') ui <- fluidPage( sliderTextInput( inputId = "slider_new", label = "Projections Range", width = '100%', choices = c('Chile','Chile-Argentina'), selected = 'Chile-Argentina' ), materialSwitch( inputId ='switch_slider', # 修复拼写错误:swithc_slider → switch_slider label = tags$p("显示法国数据"), value = FALSE ), htmlOutput('chart_1') ) server <- function(input, output, session) { # 监听开关状态,动态禁用/启用滑块 observe({ updateSliderTextInput( session, inputId = "slider_new", disabled = input$switch_slider ) }) output$chart_1 <- renderUI({ # 优先判断开关状态:开启时显示法国图表 if(input$switch_slider){ hc_data_3 %>% hchart( "line", hcaes(x = year, y = pop), showInLegend = TRUE, color = "#63696b", name = "法国人口" ) } else { # 开关关闭时,根据滑块选择显示对应图表 if(input$slider_new == "Chile"){ hc_data_1 %>% hchart( "line", hcaes(x = year, y = pop), showInLegend = TRUE, color = "#63696b", name = "智利人口" ) } else { # 显示智利-阿根廷组合图表 hc_data_1 %>% hchart( "line", hcaes(x = year, y = pop), showInLegend = TRUE, color = "#63696b", name = "智利人口" ) %>% hc_add_series( hc_data_2, "spline", color = "gray", hcaes(x = year, y = pop), showInLegend = TRUE, name = "阿根廷人口" ) } } }) } shinyApp(ui = ui, server = server)
关键修改说明
- 修复开关ID拼写错误:原代码中
swithc_slider改为switch_slider,确保输入能被正确监听 - 添加滑块禁用逻辑:通过
observe监听开关状态,使用updateSliderTextInput动态设置disabled参数 - 重构图表渲染逻辑:
- 优先判断开关状态,开启时直接渲染法国数据
- 开关关闭时,根据滑块选择分别渲染智利或智利-阿根廷组合图表
- 优化数据复用:直接使用预定义的
hc_data_*数据集,避免重复过滤gapminder
内容的提问来源于stack exchange,提问作者Cassio DS
相关产品推荐
相关产品推荐

