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

R Highcharter堆叠柱状图自定义颜色未在图例显示的解决问询

解决Highcharts堆叠柱状图图例不显示自定义颜色的问题

问题核心:你只给单个数据点设置了color,但Highcharts图例的颜色默认读取的是**整个系列(series)**的color属性,而非数据点的颜色,所以图例用了默认值。

解决方法:给每个hc_add_series()添加对应的color参数,指定该系列的图例颜色(如果需要图例显示图案填充,也可以把图案配置放在这里)。

修改后的代码如下:

highchart() %>%
  hc_chart(type = "column") %>%
  hc_add_dependency("modules/pattern-fill.js") %>%
  hc_xAxis(categories = c('Day 1', 'Day 2'), tickmarkPlacement = "on") %>%
  hc_yAxis(title = list(text = "Value")) %>%
  hc_plotOptions(column = list(stacking = "normal")) %>%
  hc_plotOptions(line = list (datalabels = list(enabled = TRUE), enableMouseTracking = FALSE)) %>%
  hc_add_series( 
    name = "Var1", 
    # 给系列指定颜色,对应图例显示的颜色
    color = "blue",
    data = list(list(y = 2, color="blue"), 
                list(y = 4, color = list(pattern = list(path = 'M 0 0 L 10 10 M 9 -1 L 11 1 M -1 9 L 1 11', width = 10, height = 10, color = 'blue')))),
    showInLegend = T) %>% 
  hc_add_series(
    name = "Var2", 
    # 给系列指定颜色,对应图例显示的颜色
    color = "red",
    data = list(list(y = 3, color="red"), 
                list(y = 5, color = list(pattern = list(path = 'M 0 0 L 10 10 M 9 -1 L 11 1 M -1 9 L 1 11', width = 10, height = 10, color = 'red')))),
    showInLegend = T)

如果希望图例也显示图案填充样式,只需要把系列的color换成图案配置即可,比如Var1的系列color改成:

color = list(pattern = list(path = 'M 0 0 L 10 10 M 9 -1 L 11 1 M -1 9 L 1 11', width = 10, height = 10, color = 'blue'))

这样图例就会显示对应的图案,同时数据点的自定义样式也会保留。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 05:07:22