使用 ChartJS 堆叠浮动水平条

Sou*_*Das 1 javascript charts bar-chart chart.js

我正在尝试使用ChartJS实现堆叠水平浮动条形图,但我遇到了一个不寻常的行为。有人可以帮忙为什么会发生这种情况吗?我正在使用的代码是:

<html>
<head>
    <title>Floating Bars</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
    <style>
        canvas {
            -moz-user-select: none;
            -webkit-user-select: none;
            -ms-user-select: none;
        }
    </style>
</head>

<body>
    <div>
        <canvas id="canvas" height="100"></canvas>
    </div>
    <script>         
      window.onload = function() {
         var ctx = document.getElementById('canvas').getContext('2d');
         window.myBar = new Chart(ctx, {
            type: 'horizontalBar',
            data:{
               labels:[1],
               datasets:[
               {
                 label:'data',
                 data:[[-3, 5]],
                 backgroundColor: 'lightblue'
               },
               {
                 label:'data',
                 data:[[6,8]],
                 backgroundColor: 'lightblue'
               },
               {
                 label:'data',
                 data:[[10, 11]],
                 backgroundColor: 'lightblue'
               }
               ]
            },
            options: {
               responsive: true,
               scales: {
                xAxes: [{
                  stacked : true,

                 }],
                 yAxes: [{
                  stacked : true,

                 }]
               },
               legend: {
                 position: 'top',
               },
               title: {
                 display: true,
                 text: 'Horizontal Floating Bars'
               }
            }
         });
      };
    </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

以下代码的输出是: 在此输入图像描述

现在,如果我们将代码与绘制的数据进行比较,我们会看到第一个和第二个数据集(即 [-3,5] 和 [6,8])正确绘制,但第三个数据集不是绘制在 [10, 11] 被绘制在 [16,17] 处,即在前面的 6 上加上 10。有人可以解释一下原因吗?

umi*_*der 5

原因是您将值堆叠在xAxis.

只需按如下方式定义 xAxis,即可获得所需的结果。

xAxes: [{
  stacked: false,
}]
Run Code Online (Sandbox Code Playgroud)

xAxes: [{
  stacked: false,
}]
Run Code Online (Sandbox Code Playgroud)
window.myBar = new Chart(document.getElementById('canvas'), {
  type: 'horizontalBar',
  data: {
    labels: [1],
    datasets: [{
        label: 'data 1',
        data: [[-3, 5], [6, 8], [10, 11]],
        backgroundColor: 'lightblue'
      },
      {
        label: 'data 2',
        data: [[6, 8]],
        backgroundColor: 'lightblue'
      },
      {
        label: 'data 3',
        data: [[10, 11]],
        backgroundColor: 'lightblue'
      }
    ]
  },
  options: {
    responsive: true,
    scales: {
      xAxes: [{
        stacked: false,
      }],
      yAxes: [{
        stacked: true,
      }]
    },
    legend: {
      position: 'top',
    },
    title: {
      display: true,
      text: 'Horizontal Floating Bars'
    }
  }
});
Run Code Online (Sandbox Code Playgroud)