如何使ChartJS比最高值稍微大一点,以正确显示高于最高柱的值?
这里第二个值(14)显示为一半,第三个(15)甚至没有显示。
这是代码:
var ctx = document.getElementById('chart-hour');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['09h - 10h', '10h - 11h', '11h - 12h', '12h - 13h', '13h - 14h', 'PAUSE DEJ', '15h - 16h', '16h - 17h', '17h - 18h'],
datasets: [{
label: '',
data: [0,14,15,7,1,0,0,0,0],
backgroundColor: [
'rgba(54, 162, 235, 0.6)',
'rgba(54, 162, 235, 0.6)',
'rgba(54, 162, 235, 0.6)',
'rgba(54, 162, 235, 0.6)',
'rgba(54, 162, 235, 0.6)',
'rgba(54, 162, 235, 0.6)',
'rgba(54, 162, 235, 0.6)',
'rgba(54, 162, 235, 0.6)',
'rgba(54, 162, 235, 0.6)'
],
borderColor: [
'rgba(54, 162, 235, 1)',
'rgba(54, 162, 235, 1)',
'rgba(54, 162, 235, 1)',
'rgba(54, 162, 235, 1)',
'rgba(54, 162, 235, 1)',
'rgba(54, 162, 235, 1)',
'rgba(54, 162, 235, 1)',
'rgba(54, 162, 235, 1)',
'rgba(54, 162, 235, 1)'
],
borderWidth: 1
}]
},
options: {
legend: {
display: false
},
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
并且该插件用于显示值:
Chart.plugins.register({
afterDatasetsDraw: function(chart) {
var ctx = chart.ctx;
chart.data.datasets.forEach(function(dataset, i) {
var meta = chart.getDatasetMeta(i);
if (!meta.hidden) {
meta.data.forEach(function(element, index) {
// Draw the text in black, with the specified font
ctx.fillStyle = 'rgb(20, 20, 20)';
var fontSize = 15;
var fontStyle = 'normal';
var fontFamily = 'Montserrat';
ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily);
// Just naively convert to string for now
var dataString = dataset.data[index].toString();
// Make sure alignment settings are correct
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
var padding = 0;
var position = element.tooltipPosition();
ctx.fillText(dataString, position.x, position.y - (fontSize / 2) - padding);
});
}
});
}
});
好的,我找到了一种方法:
将值放在数组中并获得最高值。
然后,如果最高值为0,则在tAxes中设置max: 10
如果最高值大于0,则将10添加到最高值,将其放入变量然后将其传递给max: