使用 Chartjs 的水平堆栈栏和线性栏

问题描述 投票:0回答:1

我正在尝试使用 Chartjs 创建机器事件的水平堆栈条形图和速度的线性图表。机器事件数据具有开始和结束时间,速度具有时间数据。我能够显示水平堆栈栏,但我似乎无法显示线性图表。请帮忙

这是一个例子。 https://jsfiddle.net/freakazoa/n3dc6m9r/1/

下面的示例代码:

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 }
      ]
    ],
    backgroundColor: "orange",
     type:'line',
     yAxisID:'y2'
  },
  
],


},
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 :true,
    display: true,
    position: 'right',
    title: {
          display: true,
          text: 'Speed'
     },
    min: 0,
    max: 100
  },
  x: {
    type: 'time',
    time: {
      // Luxon format string
      tooltipFormat: 'DD'
    },
    min: new Date('2021-09-11T07:00:00'),
    max: new Date('2021-09-11T09:00:00')
  }
 }
 }
});

此处输出图表(不显示速度):

chart.js
1个回答
0
投票

速度线图的

data
是一个嵌套数组。删除额外的方括号,使其成为一维数组。

  {
    label: 'Speed',
    data: [
      {
        x: new Date('2021-09-11T07:00:00'),
        y: 50,
      },
      {
        x: new Date('2021-09-11T09:00:00'),
        y: 30,
      },
    ],
    backgroundColor: 'orange',
    type: 'line',
    yAxisID: 'y2',
  },

演示@StackBlitz

© www.soinside.com 2019 - 2024. All rights reserved.