如何在highcharter柱状图中添加独立的百分比副Y轴(无需对应系列)
Highcharter实现类似ggplot的双Y轴(数值+百分比)
你可以通过绑定副Y轴到主Y轴并自定义刻度格式化函数的方式,实现和ggplot一致的双Y轴效果,无需添加额外的百分比系列,也就不会出现隐藏系列后副Y轴刻度消失的问题。
核心思路
ggplot的副Y轴是基于主Y轴数值的转换计算,而非独立的系列数据。在Highcharter中,我们可以通过linkedTo参数将副Y轴与主Y轴关联,再用labels.formatter将主Y轴的刻度值转换为百分比显示。
完整代码实现
首先准备示例数据:
set.seed(1234) df <- data.frame( Name = LETTERS[1:5], Type = paste0("Type ", c(1, 1, 2, 2, 1)), Value = rnorm(5, 150, 10) ) total_value <- sum(df$Value) # 计算总数值,用于百分比转换
然后绘制Highcharter图表:
library(highcharter) highchart2() |> hc_plotOptions( column = list( borderWidth = 0, stacking = "normal", tooltip = list( # 自定义tooltip,同时显示数值和百分比 formatter = JS(paste0("function() { var percent = (this.y / ", total_value, ").toFixed(2) + '%'; return '<b>' + this.series.name + '</b><br/>' + this.x + ': ' + this.y.toFixed(2) + ' (' + percent + ')'; }")) ) ) ) |> hc_add_series(data = df, hcaes(x = Type, y = Value, group = Name), type = "column") |> hc_xAxis(type="category") |> hc_yAxis_multiples( # 主Y轴:显示数值 list(lineWidth = 0, title = list(text="Amount")), # 副Y轴:显示百分比,关联主Y轴 list( opposite = TRUE, title = list(text="Percentage"), linkedTo = 0, # 绑定到索引为0的主Y轴 labels = list( # 将主Y轴刻度值转换为百分比 formatter = JS(paste0("function() { return (this.value / ", total_value, ").toFixed(2) + '%'; }")) ) ) )
关键参数说明
linkedTo = 0:将副Y轴与主Y轴(索引0)绑定,副Y轴的刻度范围、刻度位置完全跟随主Y轴,无需单独设置min/max。labels.formatter:使用JavaScript函数将每个刻度值除以总数值,转换为带百分比符号的字符串,实现类似ggplot的副Y轴效果。- 自定义tooltip:让鼠标悬停时同时展示原始数值和对应的百分比,提升图表可读性。
内容的提问来源于stack exchange,提问作者iamklager
相关产品推荐
相关产品推荐

