堆栈在条形图中分组xAxes

时间:2018-03-28 11:00:55

标签: javascript chart.js chart.js2

我正在使用Chart.js 2.7.0并且我想使用xAxes堆叠条形图,但按类型分组。

假设我有这样的事情: enter image description here

我想将值49和59堆叠在一个条形中,将29堆叠在一起。

当我使用堆叠的选项时,它会堆叠所有内容...... 它变为:enter image description here

当我尝试将xAxisID添加到数据集时,隐藏了id为x-axis-1的第二个数据集,根本不可见。 X轴看起来像是重复的...... 看看它的片段。

 var ctx = document.getElementById("chart1").getContext('2d');
 var ctx2 = document.getElementById("chart2").getContext('2d');
 var labels = [
      "2018_4",
      "2018_5",
      "2018_6",
      "2018_7",
      "2018_8",
      "2018_9",
      "2018_10",
      "2018_11",
    ];
 var data = {
    "labels": labels,
    "datasets": [
    {
      "label": "t1",
       xAxisID: "x-axis-0",
      "data": [
       29,19,26,28,20,21,11
      ],
      backgroundColor: 'blue'
    },
    {
      "label": "t1_SUM",
       xAxisID: "x-axis-0",
      "data": [
       32,29,36,38,30,31,31
      ],
      backgroundColor: 'red'
    },
    {
      "label": "t2",
      xAxisID: "x-axis-1",
      "data": [
      49,37,39,40,15,34,36,52
      ],
      backgroundColor: 'blue'
    },
     {
      "label": "t2_SUM",
      xAxisID: "x-axis-1",
      "data": [
      59,47,49,50,25,44,46,62
      ],
      backgroundColor: 'red'
    }
    ]
  };
  new Chart(ctx, {
  type: "bar",
  data: data,
  options: {
    scales: {
      xAxes: 
      [
      {
       stacked: true,
       id: "x-axis-0",
      },
       {
       stacked: true,
       id: "x-axis-1",
      }
      ],
    }
  }});
  
   var data2 = {
    "labels": labels,
    "datasets": [
    {
      "label": "t1",
      "data": [
       29,19,26,28,20,21,11
      ],
      backgroundColor: 'blue'
    },
    {
      "label": "t1_SUM",
      "data": [
       32,29,36,38,30,31,31
      ],
      backgroundColor: 'red'
    },
    {
      "label": "t2",
      "data": [
      49,37,39,40,15,34,36,52
      ],
      backgroundColor: 'blue'
    },
     {
      "label": "t2_SUM",
      "data": [
      59,47,49,50,25,44,46,62
      ],
      backgroundColor: 'red'
    }
    ]
  };
  
   new Chart(ctx2, {
  type: "bar",
  data: data2,
  options: {
    scales: {
      xAxes: 
      [
      {
       stacked: false,
      }
      ],
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="chart1"></canvas>
<canvas id="chart2"></canvas>
<canvas id="chart3"></canvas>

从这个片段我想连接

  • t1和t1_SUM
  • t2和t2_SUM

1 个答案:

答案 0 :(得分:0)

确定,

我误读了文档。 我应该在数据集中使用堆栈选项然后它正在工作。 对不起麻烦...