如何使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 :(得分:0)
好吧,我找到了一种方法:
将值放入数组中并获得最大值。
然后,如果最大值为0,则在yAxes中设置max: 10
如果最大值大于0,则将最大值加10,将其放入变量中,然后将其传递给max: