Chartjs-Display legend of grouped data (different colors) in chart

0👍

You only provide a single dataset so you will get only 1 legend item. This legend item uses the first backgroundColor it sees as it’s colour for the legend.

To achieve what you want you need to use 3 different datasets, each with a single static backgroundColor.
Then you can either use object notation to match the points to the correct X label or you can pass X amount of null values to fill up the space

0👍

Solution based on LeeLenalee answer

const ctx = document.getElementById("myChart").getContext("2d");

const labels = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M"];

const group1Data = [21, 34, 21, 90];
const group2Data = [88, 88, 22, 11, 10];
const group3Data = [62, 55, 96, 62];

const getResultData = (mainIndex, ...data) => data.reduce((acc, data, index) => {
  if (mainIndex === index) return acc.concat(data);
  return acc.concat(data.map(() => null));
}, []);

const groups = [
  {
    label: 'Group 1',
    data: getResultData(0, group1Data, group2Data, group3Data),
    backgroundColor: 'yellow'
  },
  {
    label: 'Group 2',
    data: getResultData(1, group1Data, group2Data, group3Data),
    backgroundColor: 'orange'
  },
  {
    label: 'Group 3',
    data: getResultData(2, group1Data, group2Data, group3Data),
    backgroundColor: 'hotpink'
  }
];

const myBarChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels,
    datasets: groups.map((group) => ({
      ...group,
      barPercentage: groups.length
    }))
  },
  options: {
    indexAxis: 'y',
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="myChart" width="350" height="175"></canvas>

Leave a comment