Chartjs-ChartJs – stacked bar chart with groups – how to create second x-axis with stack id

2πŸ‘

βœ…

To have the additional labels aligned with the stack group bars, you can define the option categoryPercentage: 1 on each dataset.

For further information, consult the chapters Dataset Configuration and barPercentage vs categoryPercentage of the Chart.js bar documentation.

Further you’ll have to define several x-axes as shown in your amended code below.

new Chart('c', {
  type: 'bar',
  data: {
    labels: ["1.1.2021", "2.1.2021"],
    datasets: [{
        label: 'First Time Visitor England',
        data: [10, 3],
        stack: "first-time-visitors",
        backgroundColor: "#f5a0a7",
        categoryPercentage: 1
      },
      {
        label: 'Repeating Visitors England',
        data: [20, 6],
        stack: "repeat-visitors",
        backgroundColor: "#e75177",
        categoryPercentage: 1
      },
      {
        label: 'First Time Visitor Sweden',
        data: [7, 0],
        stack: "first-time-visitors",
        backgroundColor: "#924565",
        categoryPercentage: 1
      },
      {
        label: 'Repeating Visitors Sweden',
        data: [9, 16],
        stack: "repeat-visitors",
        backgroundColor: "#2979a7",
        categoryPercentage: 1
      }
    ]
  },
  options: {
    tooltips: {
      mode: 'x'
    },
    scales: {
      xAxes: [{
          ticks: {
            display: false
          }
        },
        {
          type: 'category',
          offset: true,
          labels: ['first-time-visitors', 'repeat-visitors', 'first-time-visitors', 'repeat-visitors'],
          gridLines: {
            display: false
          }
        },
        {
          offset: true,
          gridLines: {
            display: false
          }
        }
      ],
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="c" width="400" height="200"></canvas>

Leave a comment