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

如何在Highcharter中预先选中一个或多个分组元素

解决方案

要实现默认只显示指定变体(如blonde和coke)、其余变体隐藏的效果,可以通过Highcharts的series.visible配置结合JavaScript回调来实现,完美适配你用group参数生成多系列的场景。

修改后的完整代码

library(tidyverse)
library(highcharter)
library(viridis)

df <- tibble(item_name = c('beer','beer','soft drink','soft_drink'),
             units = c(15,50,25,10),
             variant_name = c('blonde','white','coke','lemonade'))

cols = as.vector(scales::viridis_pal(option = "turbo", direction = 1)(length(unique(df$variant_name))))

# 定义需要默认显示的变体列表
target_variants <- c('blonde', 'coke')

df %>%
  group_by(item_name) %>%
  arrange(desc(units)) %>%
  ungroup() %>%
  hchart(
    "column", hcaes(x = item_name, y = units, group = variant_name),
    stacking = "normal"
  ) %>%
  hc_colors(cols) %>%
  # 配置系列默认可见性逻辑
  hc_plotOptions(
    series = list(
      visible = JS(paste0("function() { return ['", paste(target_variants, collapse = "','"), "'].includes(this.name); }"))
    )
  )

核心逻辑说明

  • 借助hc_plotOptions传入JavaScript回调函数,针对每个自动生成的系列做判断:
    • this.name对应每个系列的名称(即你的variant_name字段值)
    • 只有名称在target_variants列表中的系列会默认显示,其余系列自动隐藏
  • 保留图例的原生交互性:点击隐藏的图例项可显示对应变体,点击已显示的图例项可隐藏它

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:09:24