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 excellentchartjs-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>
- [Chartjs]-How can I show Bootstrap modal when on click in individual bars in chart.js
- [Chartjs]-With Chart.js can I specify a different font size for each row of text in Chart Title?
Source:stackexchange.com