Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
Is there any way to get y of specific x which not belongs to the dataset in Chart.js graph?

I have few points eg. ({ x: 5, y: 10 }, { x: 10, y: 15 }, { x: 20, y: 25 }). Chart.js can draw a chart for me basing on these points. Is there any way to read the y value of eg. 13 using the drawn chart? I am using chart.js 2.9.3 (can't change it) and vue.js. Thanks for any advice!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!