[Chartjs]-Is there any way to get y of specific x which not belongs to the dataset in Chart.js graph?

3👍

This can be done with the following function:

function valueAt(x) {
  let xScale = chart.scales['x-axis-0'];
  let yScale = chart.scales['y-axis-0'];
  let data = chart.data.datasets[0].data;
  let index = data.findIndex(o => o.x >= x);
  let prev = data[index - 1];
  let next = data[index];
  if (prev && next) {
    let slope = (next.y - prev.y) / (next.x - prev.x);
    return prev.y + (x - prev.x) * slope;
  }
}

Most code is copied from interpolate.js from the excellent chartjs-plugin-crosshair.

Please take a look at below runnable code and see how it works:

const chart = new Chart("chart", {
  type: 'line',
  data: {
    datasets: [{
      label: '',
      data: [{ x: 5, y: 10 }, { x: 10, y: 15 }, { x: 20, y: 25 }],
      type: 'line',
      borderColor: 'red',
      fill: false,
    }],
  },
  options: {
    responsive: false,
    scales: {
      xAxes: [{
        type: 'linear'
      }]
    }
  }
});

function valueAt(x) {
  let xScale = chart.scales['x-axis-0'];
  let yScale = chart.scales['y-axis-0'];
  let data = chart.data.datasets[0].data;
  let index = data.findIndex(o => o.x >= x);
  let prev = data[index - 1];
  let next = data[index];
  if (prev && next) {
    let slope = (next.y - prev.y) / (next.x - prev.x);
    return prev.y + (x - prev.x) * slope;
  }
}

let x = 13;
let y = valueAt(x);
console.log('x: ' + x + ' -> y: ' + y);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart" height="200"></canvas>

Leave a comment