我想重写Chart JS中的漂亮数字算法,并在y轴上仅显示两个标签(或刻度):值的最大值和最小值。这些值都是浮点数。我看到回调函数(yAxis.ticks.callback)已经确定了滴答声,所以我认为这不是这样做的地方。任何帮助,将不胜感激。

最佳答案

您可以对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 '';
}

注意:必须使用单独的数组来存储数据值(此处为dataArr),而不是内联数组。

编辑:

在y轴刻度配置中添加以下内容,以使数据点与刻度完全对齐:
min: Math.min.apply(this, dataArr),
max: Math.max.apply(this, dataArr)

ᴡᴏʀᴋɪɴɢ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>

关于javascript - Chartjs : how to show only max and min values on y-axis,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45788483/

10-09 10:18