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

如何在R的highcharter分组下钻柱状图中保持图例名称一致?

解决Highcharter分组下钻柱状图图例名称保持一致的问题

用R语言的highcharter包实现分组下钻柱状图时,下钻后图例名称会默认变为“Series 1”和“Series 2”,无法保持顶层的分组图例名称(示例中为sex的分组值)。以下是原始代码及解决方案:

原始代码

# load libraries
library(dplyr)
library(purrr)
library(tibble)
library(highcharter)

# example data
data <- as_tibble(datasets::HairEyeColor) |>
  rename_all(tolower)

# split into column and drilldown datasets
column <- data |>
  group_by(sex, hair) |>
  summarize(n = sum(n),
            # set column id to match drilldown id
            id = paste0(hair, "-", sex))

drilldown <- data |>
  group_nest(sex, hair) |>
  mutate(
    # set drilldown id to match column id
    id = paste0(hair, "-", sex),
    type = "column",
    data = data |> map(mutate, name = eye, y = n),
    data = data |> map(list_parse)
  )

# create highcharts plot
column |>
  hchart(
    "column",
    hcaes(x = hair, y = n, name = hair, drilldown = id, group = sex)
  ) |>
  hc_drilldown(
    activeAxisLabelStyle = list(textDecoration = "none"),
    allowPointDrilldown = FALSE,
    series = list_parse(drilldown)
  ) |>
  hc_yAxis(
    title = ""
  ) |>
  hc_xAxis(
    title = ""
  )

解决方案

问题出在下钻系列未指定名称,Highcharts会自动生成默认的“Series 1/2”。只需在构建drilldown数据时,给每个下钻系列添加name字段,指定为对应的分组值(即sex)即可:

修改后的完整代码

# load libraries
library(dplyr)
library(purrr)
library(tibble)
library(highcharter)

# example data
data <- as_tibble(datasets::HairEyeColor) |>
  rename_all(tolower)

# split into column and drilldown datasets
column <- data |>
  group_by(sex, hair) |>
  summarize(n = sum(n),
            # set column id to match drilldown id
            id = paste0(hair, "-", sex))

drilldown <- data |>
  group_nest(sex, hair) |>
  mutate(
    # set drilldown id to match column id
    id = paste0(hair, "-", sex),
    type = "column",
    # 新增:给下钻系列指定name为sex的分组值
    name = sex,
    data = data |> map(mutate, name = eye, y = n),
    data = data |> map(list_parse)
  )

# create highcharts plot
column |>
  hchart(
    "column",
    hcaes(x = hair, y = n, name = hair, drilldown = id, group = sex)
  ) |>
  hc_drilldown(
    activeAxisLabelStyle = list(textDecoration = "none"),
    allowPointDrilldown = FALSE,
    series = list_parse(drilldown)
  ) |>
  hc_yAxis(
    title = ""
  ) |>
  hc_xAxis(
    title = ""
  )

关键修改说明

在drilldown数据的mutate步骤中添加name = sex,让每个下钻系列都继承顶层的分组名称。这样下钻后,图例就会保持与顶层一致的“Male”和“Female”标签,而不是默认的系列编号。

内容的提问来源于stack exchange,提问作者Natalie O'Shea

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 10:34:56