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

如何在Highcharts图例上方添加文本并对齐图例项

Highcharts图例添加表头并对齐文本与数值的实现方案

一、实现图例文本与数值对齐

默认图例排版无法直接实现文本与数值的对齐,可通过开启HTML支持+自定义格式化函数来解决:

legend: {
  // 开启HTML解析
  useHTML: true,
  labelFormatter: function() {
    // 给车辆名称、百分比分别设置固定宽度与对齐方式
    return `<span style="display: inline-block; width: 120px; text-align: left;">${this.name}</span>
            <span style="display: inline-block; width: 60px; text-align: right;">${this.y}%</span>`;
  }
}

通过固定宽度的span容器,强制文本左对齐、数值右对齐,保证所有图例项排版整齐。

二、添加“Vehicle”与“Percentage”表头

Highcharts无内置图例表头配置,可通过图表渲染器(renderer)在图例上方绘制自定义文本,同时适配动态场景:

chart: {
  events: {
    load: function() {
      this.drawLegendHeaders();
    },
    redraw: function() {
      // 图例重绘时先清除旧表头,避免重复渲染
      if (this.legendHeaders) {
        this.legendHeaders.forEach(el => el.destroy());
      }
      this.drawLegendHeaders();
    }
  },
  // 封装表头绘制方法
  drawLegendHeaders: function() {
    const legend = this.legend;
    // 绘制左侧表头(Vehicle)
    const vehicleHeader = this.renderer.text('Vehicle', legend.left, legend.top - 20)
      .css({ fontSize: '14px', fontWeight: 'bold' })
      .add();
    // 绘制右侧表头(Percentage),根据图例宽度调整位置对齐数值
    const percentHeader = this.renderer.text('Percentage', legend.left + legend.width - 80, legend.top - 20)
      .css({ fontSize: '14px', fontWeight: 'bold' })
      .add();
    this.legendHeaders = [vehicleHeader, percentHeader];
  }
}

可根据实际图例项的宽度,调整percentHeader的left参数,确保表头与下方数值完全对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 02:42:15