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

ChartJs组合图表:如何将折线图数据点定位到第一个柱状图顶部

Chart.js 折线图数据点移至第一个柱状图顶部的配置方案

要将折线图的数据点从默认的分组柱状图中间位置,调整到第一个柱状图(A柱)的顶部,可通过以下两种方式实现:

方法一:使用折线图的pointOffset属性直接偏移数据点

在折线图的dataset中添加pointOffset属性,设置负数值让数据点左移,数值大小可根据图表实际尺寸微调:

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['dummy1', 'Jan 21st', 'Feb 21st', 'Mar 21st', 'Apr 21st', 'dummy2'],
    datasets: [
      {
        type: 'bar',
        label: 'A',
        data: [0, 10, 25, 18, 37, 0],
      },
      {
        type: 'bar',
        label: 'B',
        data: [0, 10, 25, 18, 37, 0],
      },
      {
        type: 'line', 
        label: 'C',
        data: [25, 25, 25, 25, 25, 25],
        fill: false,
        borderWidth: 1,
        borderColor: '#f00',
        borderDash: [5,4],
        lineTension: 0,
        steppedLine: true,
        // 负数值左移数据点,适配第一个柱状图位置,数值需根据图表宽度微调
        pointOffset: -18
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],  
      xAxes: [{
        ticks: {
          min: 'Jan 21st',
          max: 'Apr 21st',
        },
        // 开启offset确保柱子与x轴标签对齐,让偏移更准确
        offset: true
      }],
    }
  }
});

方法二:通过调整柱状图布局让折线点自然对齐

如果不想用固定偏移值,可调整柱状图的barPercentage和categoryPercentage,让第一个柱子的位置与折线点默认位置重合:

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['dummy1', 'Jan 21st', 'Feb 21st', 'Mar 21st', 'Apr 21st', 'dummy2'],
    datasets: [
      {
        type: 'bar',
        label: 'A',
        data: [0, 10, 25, 18, 37, 0],
        // 调整A柱的宽度占比
        barPercentage: 0.5,
        categoryPercentage: 0.8
      },
      {
        type: 'bar',
        label: 'B',
        data: [0, 10, 25, 18, 37, 0],
        barPercentage: 0.5,
        categoryPercentage: 0.8
      },
      {
        type: 'line', 
        label: 'C',
        data: [25, 25, 25, 25, 25, 25],
        fill: false,
        borderWidth: 1,
        borderColor: '#f00',
        borderDash: [5,4],
        lineTension: 0,
        steppedLine: true
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],  
      xAxes: [{
        ticks: {
          min: 'Jan 21st',
          max: 'Apr 21st',
        },
        offset: true
      }],
    }
  }
});

补充说明

  • pointOffset是直接针对折线数据点的偏移属性,数值需结合图表宽度、柱子数量微调,确保点精准落在第一个柱子顶部。
  • barPercentage控制单根柱子占所在类别宽度的比例,categoryPercentage控制类别总宽度占x轴刻度间距的比例,调整这两个值可改变分组柱子的布局,让折线点自然对齐第一个柱子。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 06:00:37