我开始使用CHART JS,当我想在每个小节的顶部显示数据Value时遇到问题,当鼠标悬停在小节上时,该值消失了。下一个问题是该值会裁剪在图表顶部
这是我的代码:
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:我正在使用ChartJS 2.7.3
答案 0 :(得分:1)
对于您的数据标签在顶部被裁剪的问题,您可以像这样通过布局选项将填充添加至:
layout: {
padding: {
left: 0,
right: 0,
top: 15,
bottom: 0
}
}
请参见小提琴-> https://jsfiddle.net/xys1tqfn/1/