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

在R语言Highcharts柱状图的每个柱子上添加代表life值的水平线

在Highcharts柱形图上添加水平参考线(标记life列数值)

数据准备代码

data <- gapminder::gapminder %>% 
  filter(country == 'Brazil') %>%
  mutate(life = rnorm(12, mean = 55, sd = 5),
         months = month.abb)   

原图表代码

data %>%
  mutate(months = as_factor(months)) %>%
  mutate(index = rep(c(1,2),6), .before = everything()) %>%
  hchart(
    'column',
    names = 'SQUADS',
    hcaes(x = months,
          y = lifeExp,
          group = months),
    color = rep(c('#1B3D59','lightgray'),6),
    name = 'Sales',
    pointWidth = 20,
    showInLegend = FALSE
  )

需求说明

希望在每个柱子对应的x轴位置上,添加短横线样式的水平线,标记life列的数值(效果为每个柱子上方对应高度有一条黑色短横线)。

解决方案代码

data %>%
  mutate(months = as_factor(months)) %>%
  mutate(index = rep(c(1,2),6), .before = everything()) %>%
  hchart(
    'column',
    names = 'SQUADS',
    hcaes(x = months,
          y = lifeExp,
          group = months),
    color = rep(c('#1B3D59','lightgray'),6),
    name = 'Sales',
    pointWidth = 20,
    showInLegend = FALSE
  ) %>%
  hc_add_series(
    data = data,
    type = "scatter",
    hcaes(x = months, y = life),
    marker = list(
      symbol = "line",
      lineWidth = 20,
      lineColor = "#000000",
      rotation = 0
    ),
    showInLegend = FALSE,
    enableMouseTracking = FALSE
  )

关键说明

  • 通过hc_add_series新增散点系列,绑定months和life字段定位横线位置
  • marker.symbol = "line"将标记设为水平线,lineWidth与柱子pointWidth保持一致,确保横线宽度匹配柱子
  • enableMouseTracking = FALSE可关闭鼠标跟踪,避免hover时出现干扰提示框

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 23:07:28