简体   繁体   English

Chartjs:如何在y轴上仅显示最大值和最小值

[英]Chartjs: how to show only max and min values on y-axis

I'd like to override the nice number algorithm in Chart JS and display only two labels (or ticks) on the y-axis: the max and min of the values. 我想覆盖Chart JS中的漂亮数字算法,并在y轴上只显示两个标签(或刻度):值的最大值和最小值。 The values are all floating point numbers. 这些值都是浮点数。 I see the callback function ( yAxis.ticks.callback) already has the the ticks figured out so I don't think this is place to do it. 我看到回调函数(yAxis.ticks.callback)已经找到了勾号,所以我不认为这是做这件事的地方。 Any help would be appreciated. 任何帮助,将不胜感激。

You can use the following callback function for y-axis ticks to achieve that : 您可以使用以下回调函数进行y轴刻度来实现:

callback: function(value, index, values) {
   if (index === values.length - 1) return Math.min.apply(this, dataArr);
   else if (index === 0) return Math.max.apply(this, dataArr);
   else return '';
}

note: you must use a separate array for data values (here it's dataArr ) , instead of an in-line one. 注意:您必须为数据值使用单独的数组(此处为dataArr ,而不是内联数组。

EDIT : 编辑:

add the following in your y-axis ticks config to make the data-points perfectly aligned with the ticks : 在y轴ticks配置中添加以下内容,使数据点与刻度完全对齐:

min: Math.min.apply(this, dataArr),
max: Math.max.apply(this, dataArr)

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ᴡᴏʀᴋɪɴɢᴡᴏʀᴋɪɴɢxᴀᴍᴘʟᴇ

 var dataArr = [154.23, 203.21, 429.01, 637.41]; var chart = new Chart(ctx, { type: 'line', data: { labels: ['Jan', 'Feb', 'Mar', 'Apr'], datasets: [{ label: 'LINE', data: dataArr, backgroundColor: 'rgba(0, 119, 290, 0.2)', borderColor: 'rgba(0, 119, 290, 0.6)', fill: false, tension: 0 }] }, options: { scales: { yAxes: [{ ticks: { min: Math.min.apply(this, dataArr), max: Math.max.apply(this, dataArr), callback: function(value, index, values) { if (index === values.length - 1) return Math.min.apply(this, dataArr); else if (index === 0) return Math.max.apply(this, dataArr); else return ''; } } }] } } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script> <canvas id="ctx"></canvas> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM