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

如何在Highchart中自定义阶梯折线图的水平、垂直线条粗细

阶梯线效果示意

实现方案

Highcharts本身没有原生支持阶梯线不同分段设置不同线宽的属性,可以通过操作图表渲染后的SVG路径实现,完整可运行的配置示例如下:

Highcharts.chart('container', {
  chart: {
    type: 'line',
    events: {
      render: function() {
        // 遍历所有阶梯系列,单系列的话直接取this.series[0]即可
        this.series.forEach(series => {
          if (!series.options.step || !series.graph) return;
          const pathEl = series.graph.element;
          const pathData = pathEl.getPathData();
          const render = this.renderer;
          const seriesColor = series.color;
          let prevX, prevY;
          let verticalSegPath = [];

          pathData.forEach((seg, index) => {
            if (seg.type === 'M') {
              prevX = seg.values[0];
              prevY = seg.values[1];
              verticalSegPath.push(seg);
            } else if (seg.type === 'L') {
              const currX = seg.values[0];
              const currY = seg.values[1];
              // 水平段单独渲染,设置粗线
              if (currY === prevY) {
                render.path(['M', prevX, prevY, 'L', currX, currY])
                  .attr({
                    stroke: seriesColor,
                    'stroke-width': 4, // 水平段线宽,可自定义
                    fill: 'none',
                    'stroke-linecap': 'round'
                  })
                  .add(series.group);
              } 
              // 垂直段保留到原始路径
              else if (currX === prevX) {
                verticalSegPath.push(seg);
              }
              prevX = currX;
              prevY = currY;
            }
          });
          // 原始路径只渲染垂直段,设置细线
          pathEl.setAttribute('d', verticalSegPath.map(item => `${item.type} ${item.values.join(' ')}`).join(' '));
          pathEl.setAttribute('stroke-width', 1); // 垂直段线宽,可自定义
        })
      }
    }
  },
  xAxis: {
    categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul']
  },
  series: [{
    step: 'left', // 支持left/center/right三种阶梯模式
    data: [1, 3, 2, 4, 3, 5, 6],
    lineWidth: 0 // 原始线宽设为0避免默认路径和自定义路径重叠
  }]
});

注意事项

  • 该方案兼容所有阶梯类型,图表重绘(数据更新、窗口缩放等)时会自动重新计算路径,无需额外处理
  • 可自行调整代码中水平段、垂直段的stroke-width数值适配需求
  • 多系列场景下也可正常运行,无需修改核心逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:09:03