Reputation: 1584
I'm using chart.js on a project due to its MIT license instead of the Highcharts framework. There is one thing that can be easily done on highcharts that I cannot seem to do with Charts.js, which is having labels on top of my bars charts, such as in the demo below:
In highcharts documentation those numbers on each stack of this bar chart is configued in this manner:
plotOptions: {
series: {
dataLabels: {
enabled: true
}
}
I've extensively read Chart.js documentation and did not find a way of accomplishing the same visualization nor examples in forums. Is there a way of showing numbers over the bars using Chart.js barcharts?
Upvotes: 1
Views: 5442
Reputation: 8134
It is possible to do this with Chart.js. However you need the datalabels plugin. In this script you can see how it is implemented. With this plugin charts of type 'bar'
will automatically add labels to the center.
var ctx2 = document.getElementById("stack-chart");
var stackChart1 = new Chart(ctx2, {
type: 'bar',
options: {
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true,
ticks: {
beginAtZero: true
}
}]
},
legend: {
display: false,
labels: {
fontSize: 20,
fontColor: '#595d6e',
}
},
tooltips: {
enabled: false
},
plugins: {
datalabels: {
formatter: (value, ctx) => {
return;
},
color: '#fff',
}
}
},
data: {
labels: ['ㅇㅇ마트', 'ㅂㅂ프라자', 'ㅈㅈ랜드', 'ㅁㅁ마트', 'ㄴㄴ플러스'],
datasets: [{
backgroundColor: "#5e63b4",
data: [5600, 5600, 10000, 4600, 5600]
}, {
backgroundColor: "#e11738",
data: [6000, 3000, 1600, 6400, 2300]
}]
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/0.7.0/chartjs-plugin-datalabels.min.js"></script>
<canvas id="stack-chart" width="1360" height="450"></canvas>
Upvotes: 6