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

Chart.js横向堆叠柱状图与折线图:速度折线图不显示求助

解决Chart.js横向堆叠柱状图与速度折线图共存时折线不显示的问题

问题原因分析

你的代码中导致折线图不显示的核心问题有3个:

  • 速度折线图的data格式错误,嵌套了多余的二维数组,Chart.js无法正确解析坐标点
  • 右侧y轴(y2)设置了stacked: true,折线图不需要堆叠属性,该配置会干扰折线图的渲染逻辑
  • 横向柱状图设置了indexAxis: 'y',但折线图的坐标映射需要明确对应时间轴(x轴)和速度轴(y2轴)

修正后的完整代码

var ctx = document.getElementById('chart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["Machine Events"],
    datasets: [{
        label: 'Autorun',
        data: [
          [new Date('2021-09-11T07:00:00'), new Date('2021-09-11T07:15:00')],
        ],
        backgroundColor: "green",
        yAxisID: 'y1'
      },
      {
        label: 'Trouble',
        data: [
          [new Date('2021-09-11T07:15:00'), new Date('2021-09-11T07:30:00')],
        ],
        backgroundColor: "red",
        yAxisID: 'y1'
      },
      {
        label: 'Autorun',
        data: [
          [new Date('2021-09-11T07:30:00'), new Date('2021-09-11T07:30:30')],
        ],
        backgroundColor: "green",
        yAxisID: 'y1'
      },
      {
        label: 'Idle',
        data: [
          [new Date('2021-09-11T07:30:30'), new Date('2021-09-11T08:00:00')],
        ],
        backgroundColor: "yellow",
        yAxisID: 'y1'
      },
      {
        label: 'Speed',
        // 修正:去掉多余的数组嵌套,直接传入坐标点数组
        data: [
          { x: new Date('2021-09-11T07:00:00'), y: 50 },
          { x: new Date('2021-09-11T09:00:00'), y: 30 }
        ],
        borderColor: "orange", // 折线图用borderColor而非backgroundColor
        type: 'line',
        yAxisID: 'y2',
        fill: false // 关闭填充,仅显示折线
      },
    ]
  },
  options: {
    responsive: false,
    indexAxis: 'y',
    plugins: {
      legend: {
        position: 'top',
      },
      title: {
        display: true,
        text: 'Chart.js Floating Horizontal Bar Chart'
      }
    },
    scales: {
      y1: {
        stacked: true
      },
      y2: {
        type: 'linear',
        // 修正:移除stacked属性,折线图不需要堆叠
        display: true,
        position: 'right',
        title: {
          display: true,
          text: 'Speed'
        },
        min: 0,
        max: 100
      },
      x: {
        type: 'time',
        time: {
          tooltipFormat: 'DD'
        },
        min: new Date('2021-09-11T07:00:00'),
        max: new Date('2021-09-11T09:00:00')
      }
    }
  }
});

关键修正点说明

  1. 修正折线图数据格式:将速度数据集的data从[[{x:..., y:...}]]改为[{x:..., y:...}, ...],去掉多余的数组嵌套,让Chart.js能正确识别每个坐标点
  2. 调整折线图样式属性:折线图应使用borderColor定义线条颜色,而非backgroundColor,同时设置fill: false避免填充区域
  3. 移除y2轴的堆叠属性:删除y2配置中的stacked: true,折线图不需要堆叠,该属性会导致折线无法正确映射到y轴刻度
  4. 确保轴映射正确:折线图的yAxisID绑定到右侧的y2轴,x轴为时间轴,坐标点的x对应时间、y对应速度值,与轴配置完全匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 19:29:51