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

如何用Highcharter实现百分比堆叠柱状图与折线图组合?

Highcharter 百分比堆叠柱状图+折线图数值修正方案

当使用stacking = 'percent'的堆叠柱状图搭配折线图时,折线图默认会继承柱状图的百分比轴刻度,导致实际数值被错误转换为百分比显示。解决核心是为折线图配置独立的原始数值y轴,与柱状图的百分比轴分离。

修正后的代码示例

假设你的测试数据结构如下:

informatik_df <- data.frame(
  Jahr = c(2020, 2021, 2022, 2023),
  CatA = c(10, 15, 20, 25),
  CatB = c(20, 25, 30, 35),
  CatC = c(30, 35, 40, 45),
  LineValue = c(60, 75, 90, 105) # 折线对应实际数值
)

修改自定义函数create_stacked_bar:

create_stacked_bar <- function(df) {
  # 先将分类列转为长格式(适配堆叠柱状图数据结构)
  df_long <- tidyr::pivot_longer(df, cols = -c(Jahr, LineValue), names_to = "variable", values_to = "value")
  
  hchart(df_long, "column", hcaes(x = Jahr, y = value, group = variable)) %>%
    # 配置柱状图为百分比堆叠
    hc_plotOptions(
      column = list(
        stacking = "percent",
        dataLabels = list(enabled = TRUE, format = "{y:.1f}%")
      ),
      # 指定折线图使用第二个y轴
      line = list(yAxis = 1, marker = list(enabled = TRUE))
    ) %>%
    # 配置双y轴:左侧百分比轴,右侧原始数值轴
    hc_yAxis(
      # 第一个轴(柱状图用)
      list(
        title = list(text = "占比"),
        labels = list(format = "{value}%"),
        min = 0,
        max = 100
      ),
      # 第二个轴(折线图用)
      list(
        title = list(text = "实际数值"),
        opposite = TRUE,
        labels = list(format = "{value}"),
        min = 0
      )
    ) %>%
    # 添加折线图系列,绑定原始数值列
    hc_add_series(
      data = df$LineValue,
      name = "实际数值",
      type = "line",
      hcaes(x = Jahr, y = LineValue)
    ) %>%
    hc_title(text = "百分比堆叠柱状图+折线图") %>%
    hc_xAxis(title = list(text = "年份")) %>%
    hc_legend(enabled = TRUE)
}

# 生成图表
create_stacked_bar(informatik_df)

关键配置说明

  • stacking = "percent":确保柱状图按百分比堆叠,而非普通数值堆叠
  • 双y轴分离:通过hc_yAxis定义两个独立轴,左侧对应柱状图的百分比刻度,右侧对应折线图的原始数值刻度
  • 折线图绑定第二轴:在hc_plotOptions(line)中设置yAxis = 1,让折线图使用右侧的原始数值轴,避免被百分比转换影响

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 14:12:32