Reputation: 85
I m begginning with CHART JS and i've got a problem when i want to display the data Value on the top of each bar and the value disappear when my mouse is hover the bar. The next problem is the value are cropped on the top of the Chart
Here's my code :
function assignChart(ctx, dataArray) {
const dataLabel = ["Paris", "Milan", "London", "Florence", "New York", "Not specified"];
return (new Chart(ctx, {
type: 'bar',
data: {
labels: dataLabel,
datasets: [{
data: dataArray,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
events: [],
responsive: true,
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
display: false,
beginAtZero:true,
}
}]
},
animation: {
duration : 1,
onComplete : function() {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function(dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function(bar, index) {
if (dataset.data[index] > 0) {
var data = dataset.data[index];
ctx.fillText(data, bar._model.x, bar._model.y);
}
});
});
}
}
}
}));
}
Ps : i'm using ChartJS 2.7.3
Upvotes: 4
Views: 17178
Reputation: 1669
For the problem of yours the data labels getting cropped on the top, you can add padding to the through the layout option like this:
layout: {
padding: {
left: 0,
right: 0,
top: 15,
bottom: 0
}
}
See fiddle -> https://jsfiddle.net/xys1tqfn/1/
Upvotes: 9