I want to display datalables on top of eachbar(Datalabels are showing when i mouseover through the bar). I used chartdatalabels plugin to acheive this. But when i register the plugin using Chart.register(ChartDataLabels). Its throwing error and its not displaying the entire barchart.
Here is my code
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
var chartOptionsWeekly = {
responsive: true,
plugins: {
datalabels: {
anchor: 'end',
align: 'end',
labels: {
value: {
color: 'white'
}
}
}
},
legend: {
position: "top",
labels: {
fontColor: "white"
}
},
title: {
display: false,
text: "Daily Trend"
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
fontColor: 'white',
fontSize: 14,
stepSize: 20
},
scaleLabel: {
display: true,
labelString: 'Attendance Percentage',
fontColor: 'white'
}
}],
xAxes: [{
ticks: {
beginAtZero: true,
fontColor: 'white',
fontSize: 14
},
scaleLabel: {
display: true,
labelString: 'Last 7 Days',
fontColor: 'white'
}
}]
}
}
Chart.register(ChartDataLabels)
window.onload = function () {
var ctxDaily = document.getElementById("barChartWeekly").getContext("2d");
window.myBar = new Chart(ctxDaily, {
type: "bar",
plugins: [ChartDataLabels],
data: barChartDataWeekly,
options: chartOptionsWeekly
});
};
Any help would be appreciated. Thanks!
Note that you're using an outdated version of
Chart.js
, the current version is4.4.0
.Chart.register
was introduced inChart.js
version 3, it replaced formerChart.plugins.register
(see. 3.x Migration Guide -> Removed from Chart).To solve your problem, you should use
Chart.plugins.register
or even better, use the most recent version ofChart.js
.