Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Using Chart.js, I'd like to display only two labels (or ticks) on the y-axis: the max and min of the values. The values are all floating point numbers.

I'm not sure if the callback function yAxis.ticks.callback is the place to do it.

like image 532
Timothy Barmann Avatar asked Aug 21 '17 02:08

Timothy Barmann


People also ask

How do you hide ticks in Chartjs?

To also hide the tick marks themselves, add gridLines: { tickMarkLength: 0 } to the y axis definition (tested in version 2.9. 4).

How do you set a minimum value in a graph?

To set the minimum or maximum value on a value scale,In Chart Properties, click Value Scale. Enter the desired minimum and/or maximum values in the Min and Max fields, respectively.

What is utils in Chartjs?

The Utils file contains multiple helper functions that the chart. js sample pages use to generate charts. These functions are subject to change, including but not limited to breaking changes without prior notice. Because of this please don't rely on this file in production environments.


1 Answers

You can use the following callback function for y-axis ticks to achieve that :

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.

EDIT :

add the following in your y-axis ticks config to make the data-points perfectly aligned with the ticks :

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>
like image 64
ɢʀᴜɴᴛ Avatar answered Oct 20 '22 11:10

ɢʀᴜɴᴛ