2👍
✅
One solution by datalabels plugin – https://chartjs-plugin-datalabels.netlify.com/ and this options for labels:
-
anchor:'end',
==> highest element boundary -
align: top
==> the label is positioned after the anchor point, following the same direction
For small tuning, change padding
, offset
(Negative or positive), font-size and so on (A lot of control). datalabels Options
“Hello world example”:
// Change default options for ALL charts
Chart.helpers.merge(Chart.defaults.global.plugins.datalabels, {
formatter: function(value, context) {
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
},
opacity: 1,
color: 'black',
borderColor: '#11469e',
anchor: 'end', /*https://chartjs-plugin-datalabels.netlify.com/guide/positioning.html */
align: 'top', /* https://chartjs-plugin-datalabels.netlify.com/guide/positioning.html#alignment-and-offset */
font: {
weight: 'bold',
size: 14,
lineHeight: 1 /* align v center */
},
offset: 0, /* 4 by deafult */
padding:{
bottom: 0 /* 4 by deafult */
}
});
var data = {
labels: ["Africa", "Asia", "Europe", "America"],
datasets: [{
/* data */
label: "Population (millions)",
backgroundColor: ["#490A3D", "#BD1550","#E97F02", '#F8CA00'],
data: [1000,1500,2000, 2200]
}]
};
var options = {
plugins: {
// Change options for ALL labels of THIS CHART
datalabels: {
}
},
animation:{
duration: 2000 /* time in ms */
},
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
ticks: {
// Include a dollar sign in the ticks
callback: function(value, index, values) {
return '$' + value;
}
},
stacked: true
}]
}
};
var myChart = new Chart(document.getElementById("chart"), {
type: 'bar',
data: data,
options: options
});
<canvas id="chart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0"></script>
One more example (Extra hover and styling):
https://codepen.io/ezra_siton/pen/bGdYaLd
datalabels
is very cool library. For example, add $
and change 1000
to 1,000
to data in 2 lines of code.
formatter: function(value, context) {
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
},
Related: How to print a number with commas as thousands separators in JavaScript
Source:stackexchange.com