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

如何修改highcharter堆叠柱状图悬停高亮规则 仅高亮单个数据项

highcharter堆叠柱状图悬停单块高亮实现方案

问题背景

现有包含group(分组)、item(项目)、index(索引)、hours(时长)字段的数据框,构造代码如下:

library(dplyr)
library(highcharter)

data <- data.frame(
  group=c("group_1","group_1","group_2","group_1","group_2","group_2","group_2","group_1"),
  item=c("item_A","item_A","item_C","item_B","item_D","item_D","item_C","item_B"),
  index=c(1,2,1,1,2,3,3,3),
  hours=c(10,20,20,20,30,10,20,10)
) %>%
  arrange(index)

初始使用highcharter绘制堆叠柱状图的代码如下,可实现基础堆叠效果、自定义tooltip、图例点击切换整组显示隐藏的功能:

hchart(data,
       "column",
       hcaes(x = index, y = hours, group = group),
       tooltip = list(pointFormat = "{point.group} <br> {point.item} <br> Hours: {point.hours}")) %>%
  hc_plotOptions(column = list(
      dataLabels = list(enabled = FALSE),
      stacking = "normal",
      borderWidth= 0,
      enableMouseTracking = TRUE)) %>%
  hc_xAxis(title = list(text = "index"))

当前存在的问题:鼠标悬停在单个数据块上时,会自动高亮同属一个group的所有同索引位置的堆叠数据块,需要调整为仅高亮当前悬停的单个数据块,同时保留原有的图例点击切换整组显隐的交互功能。

实现代码

该需求可通过调整柱形图的状态配置、追踪逻辑实现,修改后的完整代码如下:

hchart(data,
       "column",
       hcaes(x = index, y = hours, group = group),
       tooltip = list(pointFormat = "{point.group} <br> {point.item} <br> Hours: {point.hours}")) %>%
  hc_plotOptions(column = list(
      dataLabels = list(enabled = FALSE),
      stacking = "normal",
      borderWidth= 0,
      enableMouseTracking = TRUE,
      # 新增配置开始
      stickyTracking = FALSE,
      findNearestPointBy = "xy",
      states = list(
        hover = list(
          enabled = TRUE,
          brightness = 0.1,
          opacity = 1
        ),
        inactive = list(
          opacity = 1
        )
      )
      # 新增配置结束
  )) %>%
  hc_xAxis(title = list(text = "index"))

参数说明

  • stickyTracking = FALSE:关闭鼠标在柱形区域附近时自动吸附追踪同系列点的默认逻辑
  • findNearestPointBy = "xy":将鼠标最近点的匹配规则从「同x轴下匹配同系列点」改为「按xy二维坐标精确匹配单个点」,避免选中同索引下的其他同组数据块
  • states.inactive.opacity = 1:取消默认的非激活点自动变暗效果,仅保留点击图例时整组隐藏的交互,不会影响原有图例功能
  • states.hover.brightness = 0.1:给悬停的单个数据块加轻微提亮效果,强化高亮区分度,不需要可以删除该参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 15:00:53