Chart js 在顶部显示级别。 (带堆叠组的条形图)

Chart js show levels on top. (Bar chart with Stacked group)

这里我实现了基本的堆叠组条形图

级别是 'Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange' 这里有两个堆叠组 one, two

<canvas id="myChart"></canvas>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
    var ctx = document.getElementById('myChart').getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
            datasets: [{
                stack: 'one',
                label: 'one',
                data: [12, 19, 3, 5, 2, 3],
                borderWidth: 1
            },
            {
                stack: 'two',
                label: 'two',
                data: [19, 3, 5, 2, 3, 12],
                borderWidth: 1
            },
            {
                stack: 'one',
                label: 'one',
                data: [ 3, 5, 2, 3, 12, 19],
                borderWidth: 1
            },
            {
                stack: 'two',
                label: 'two',
                data: [ 2, 3, 12, 19, 3, 5],
                borderWidth: 1
            }]
        },
        options: {
            
            scales: {
    xAxes: [
      {
        stacked: true,
      }
    ],
    yAxes: [
      {
        stacked: true,
      }
    ]
  }
        }
    });
    </script>

输出:

但我想在贪婪的底部显示堆叠组级别,在顶部显示数据级别(不是每个条)

预期输出:

您需要额外定义一个type: 'category'的x轴,如下:

xAxes: [{
    stacked: true,
    position: 'top'
  },
  {
    type: 'category',
    offset: true,
    labels: ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']
  }
],

请查看您修改后的可运行代码,看看它是如何工作的:

new Chart('myChart', {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
        stack: 'one',
        label: 'one',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        stack: 'two',
        label: 'two',
        data: [19, 3, 5, 2, 3, 12],
        borderWidth: 1
      },
      {
        stack: 'one',
        label: 'one',
        data: [3, 5, 2, 3, 12, 19],
        borderWidth: 1
      },
      {
        stack: 'two',
        label: 'two',
        data: [2, 3, 12, 19, 3, 5],
        borderWidth: 1
      }
    ]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
          stacked: true,
          position: 'top'
        },
        {
          gridLines: {
                display: false
          },
          type: 'category',
          offset: true,
          labels: ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']         }
      ],
      yAxes: [{
        stacked: true,
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="100"></canvas>