I have a horizontal chart with different colors to group the data. In the code below, the chart layout displays as intended, but the legend shows only a single color (yellow). How can I force the chart to show the legend of the other two while still maintaining the layout of the chart? The legends should be "Group 1" for yellow, "Group 2" for orange, and "Group 3" for pink.
var ctx = document.getElementById("myChart").getContext("2d");
var dataArr = [21, 34, 21, 90, 88, 88, 22, 11, 10, 62, 55, 96, 62];
var dataLabelsArr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M"];
var dataColorsArr = ["yellow", "yellow", "yellow", "yellow", "orange", "orange", "orange", "orange", "orange", "hotpink", "hotpink", "hotpink", "hotpink"];
var data = {
datasets: [{
label: dataLabelsArr,
backgroundColor: dataColorsArr,
data: dataArr
}]
};
var myBarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: dataLabelsArr,
datasets: [{
data: dataArr,
backgroundColor: dataColorsArr,
label: "Group 1"
}]
},
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>
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
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>