Home > Back-end >  Get value of min/lowest label from y-axis chart
Get value of min/lowest label from y-axis chart

Time:09-23

I am trying to get the lowest y-axis label/value in my chart. The y-axis labels are dynamically/automatically added as I had intentionally not set it to begin at zero. How could I get the value of the lowest label (30 in the example below) from the chart?

I tried: myLineChart.options.scales.yAxes[0].ticks.min; but it only returns undefined:

var ctx = document.getElementById('myChart').getContext('2d');

var data = {
  labels: ["data1", "data2", "data3", "data4", "data5", "data6"],
  datasets: [{
    label: "Sample data",
    data: [128, 56, 47, 64, 125, 36],
    borderColor: "rgba(0, 128, 0, 1)"
  }]
};

var myLineChart = new Chart(ctx, {
  type: "line",
  data: data
});

console.log(myLineChart.options.scales.yAxes[0].ticks.min); // returns `undefined`
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<canvas id="myChart" width="200" height="100"></canvas>

CodePudding user response:

I did some digging through the myLineChart object and found the path to get to the y axis ticks is: myLineChart.ticks.boxes[0].chart.scales['y-axis-0'].ticks.

The snippet below shows me using that to output the lowest value.

Alternatively, if you upgrade chartJs to at least version 3.1(which is what I am using on a project) the chart object structure is much easier to navigate. In ChartJs 3.1 the answer would looke like: myLineChart.scales.y.min

var ctx = document.getElementById('myChart').getContext('2d');

var data = {
  labels: ["data1", "data2", "data3", "data4", "data5", "data6"],
  datasets: [{
    label: "Sample data",
    data: [128, 56, 47, 64, 125, 36],
    borderColor: "rgba(0, 128, 0, 1)"
  }]
};

var myLineChart = new Chart(ctx, {
  type: "line",
  data: data
});

console.log(myLineChart.boxes[0].chart.scales['y-axis-0'].ticks[myLineChart.boxes[0].chart.scales['y-axis-0'].ticks.length - 1])
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<canvas id="myChart" width="200" height="100"></canvas>

  • Related