Chartjs-Chart js grouped bar chart with individual label

0👍

You should declare and configure another x-axis. In the following example inspired by your data, I use options.scales.x.ticks.callback (see Labeling Axes | Chart.js) which allows me to inject new labels.

const ctx = document.getElementById('myChart');

new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Category 1', 'Category 2', 'Category 3', 'Category 4'],
    datasets: [{
      label: 'Dataset 1',
      data: [3, 4, 4, 2],
      stack: 'Stack 0'
    }, {
      label: 'Dataset 2',
      data: [5, 3, 4, 7],
      stack: 'Stack 0'
    }, {
      label: 'Dataset 3',
      data: [3, 0, 4, 4],
      stack: 'Stack 1'
    }, {
      label: 'Dataset 4',
      data: [2, 5, 6, 2],
      stack: 'Stack 1'
    }]
  },
  options: {
    scales: {
      x: {
        stacked: true,
        ticks: {
          font: {
            weight: 'bold'
          },
          callback: () => 'Label 1  |  Label 2'
        }
      },
      x2: {
        border: {
          display: false
        },
        grid: {
          display: false
        }
      },
      y: {
        stacked: true,
        beginAtZero: true
      }
    },
    plugins: {
      legend: {
        display: false
      }
    }
  }
});
.chart-container {
  position: relative;
  width: 600px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.2.0"></script>

<div class="chart-container">
  <canvas id="myChart"></canvas>
</div>

Leave a comment