I’m trying to create a horizontal bar chart where both the data and labels are random. I also want to incorporate a legend for each bar, similar to a donut chart. The goal is to enable removal of a specific item by selecting its corresponding legend text.
I’m considering the option of creating multiple datasets, but I’m unsure if that is the best approach.
Im using Chart.js/2.7.2/Chart.min.js
Im expecting that i could create legend for each bar
Please suggest some good ideas without multiple datasets as well
Below code i was trying for creating new datasets based on labels and values :
const newDatasets = labels.map((label, index) => ({
label: label,
data: values[index],
}));
Here is my actual code :
const labels = category;
const values = count;
const data = {
labels: labels,
datasets: [{
data: values,
backgroundColor: getBackgroundColor(labels, reportColor[0]),
borderWidth: 2,
borderRadius: 19,
borderSkipped: false,
barPercentage: 1,
categoryPercentage: 0.1
}]
};
const config = {
type: 'horizontalBar',
data,
options: {
plugins: {
datalabels: {
color: 'white',
font: {
weight: 'bold'
},
},
},
responsive: true,
maintainAspectRatio: false,
indexAxis: 'y',
legend: { display: false },
tooltips: {
cornerRadius: 10
},
scales: {
xAxes: [{
barThickness: 6,
gridLines: {
display: false,
drawBorder: false
},
scaleLabel: {
display: true,
labelString: yAxisLabel,
fontSize: 20
},
ticks: {
/*beginAtZero: true,*/
userCallback: function(label, index, labels) {
if (Math.trunc(label) === label) {
return label;
}
}
},
}],
yAxes: [{
barPercentage: 1.0,
barThickness: 20,
gridLines: {
display: false,
drawBorder: false
},
scaleLabel: {
display: true,
labelString: xAxisLabel,
fontSize: 20
},
}]
},
},
};
horizontalBarChart = new Chart(
document.getElementById("horizontalBarChart"),
config
);