1👍
✅
This is because, you have placed the plugins
array, inside your chart options, while it should be followed by (outside) your chart options.
Here is the working version of your code :
var mainlabels = ["Jose 12", "Jose 13", "Jay 12", "Jay 13", "Rob 12", "Rob 13"];
var salesbyperson = [21, 31, 21, 16, 22, 24];
var ctx = document.getElementById('canvasone').getContext('2d');
var chart = new Chart(ctx, {
type: 'bar',
data: {
labels: mainlabels,
datasets: [{
label: 'Sum of Sales',
backgroundColor: 'rgba(0, 129, 214, 0.8)',
data: salesbyperson
}]
},
options: {
tooltips: {
callbacks: {
label: function(t, d) {
if (t.datasetIndex === 1) {
var xLabel = d.datasets[t.datasetIndex].label;
var yLabel = t.yLabel + '%';
return xLabel + ': ' + yLabel;
} else if (t.datasetIndex === 0) {
var xLabel = d.datasets[t.datasetIndex].label;
var yLabel = t.yLabel >= 1000 ? '$' + t.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : '$' + t.yLabel;
return xLabel + ': ' + yLabel;
}
}
}
},
legend: {
display: false,
position: 'top',
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
callback: function(value, index, values) {
if (parseInt(value) >= 1000) {
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return '$' + value;
}
}
}
}]
}
},
plugins: [{
beforeDraw: function(chart) {
var labels = chart.data.labels;
labels.forEach(function(e, i) {
var bar = chart.data.datasets[0]._meta['0'].data[i]._model;
var dataPoint = e.split(/\s/)[1];
if (dataPoint === '12')
bar.backgroundColor = 'blue';
else if (dataPoint === '13')
bar.backgroundColor = 'green';
});
}
}]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvasone"></canvas>
Source:stackexchange.com