12👍
This can be easily achieved using a Chart.js plugin called : chartjs-plugin-datalabels.
Here is the minimum options that need to be set for this plugin to display values inside (middle) of the stacked bars :
options: { //your chart options
plugins: {
datalabels: {
display: true,
align: 'center',
anchor: 'center'
}
}
}
although, there are tons of other options that you can use to further customize these values/labels (inside bars), which can be found here.
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
var numberWithCommas = function(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};
var dataPack1 = [50000, 22000, 26000, 35000, 55000, 55000, 56000, 59000, 60000, 61000, 60100, 62000];
var dataPack2 = [0, 6000, 13000, 14000, 50060, 20030, 20070, 35000, 41000, 4020, 40030, 70050];
var dates = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
// Chart.defaults.global.elements.rectangle.backgroundColor = '#FF0000';
var bar_ctx = document.getElementById('bar-chart');
var bar_chart = new Chart(bar_ctx, {
type: 'bar',
data: {
labels: dates,
datasets: [{
label: 'SoftEnterprises, Sales',
data: dataPack1,
backgroundColor: "rgba(55, 160, 225, 0.7)",
hoverBackgroundColor: "rgba(55, 160, 225, 0.7)",
hoverBorderWidth: 2,
hoverBorderColor: 'lightgrey'
}, {
label: 'SmartSystems, Sales',
data: dataPack2,
backgroundColor: "rgba(225, 58, 55, 0.7)",
hoverBackgroundColor: "rgba(225, 58, 55, 0.7)",
hoverBorderWidth: 2,
hoverBorderColor: 'lightgrey'
}, ]
},
options: {
tooltips: {
mode: 'label',
callbacks: {
label: function(tooltipItem, data) {
return data.datasets[tooltipItem.datasetIndex].label + ": " + numberWithCommas(tooltipItem.yLabel);
}
}
},
scales: {
xAxes: [{
stacked: true,
gridLines: {
display: false
},
}],
yAxes: [{
stacked: true,
ticks: {
callback: function(value) {
return numberWithCommas(value);
},
},
}],
}, // scales
legend: {
display: true
},
plugins: {
datalabels: {
display: true,
align: 'center',
anchor: 'center'
}
}
} // options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
<canvas id="bar-chart" width="600" height="350"></canvas>
0👍
The accepted answer no longer works in the latest version of Chart.js
and chartjs-plugin-datalabels
.
If you are using Chart.js v3.7.0
and above and chartjs-plugin-datalabels v2.2.0
and above, you can register it as below:
Register the plugin to all charts:
Chart.register(ChartDataLabels);
OR only to specific charts:
var chart = new Chart(ctx, {
plugins: [ChartDataLabels],
options: {
// ...
}
})
Note: The plugin is not nested in the chart options, unlike the accepted answer.
Read more: https://chartjs-plugin-datalabels.netlify.app/guide/getting-started.html#registration