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

如何在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)

关键修改说明

  1. 修复开关ID拼写错误:原代码中swithc_slider改为switch_slider,确保输入能被正确监听
  2. 添加滑块禁用逻辑:通过observe监听开关状态,使用updateSliderTextInput动态设置disabled参数
  3. 重构图表渲染逻辑:
    • 优先判断开关状态,开启时直接渲染法国数据
    • 开关关闭时,根据滑块选择分别渲染智利或智利-阿根廷组合图表
  4. 优化数据复用:直接使用预定义的hc_data_*数据集,避免重复过滤gapminder

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:44:17