是否有办法得到特定x的y不属于Chart.js图中的数据集?



我有几点看法。({ x: 5, y: 10 }, { x: 10, y: 15 }, { x: 20, y: 25 })。chart .js可以根据这些点为我绘制一个图表。有没有办法读取eg的y值。使用绘制的图表?我正在使用chart.js 2.9.3(不能改变它)和vue.js。谢谢你的建议!

这可以通过以下函数完成:

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;
}
}

大部分代码是从优秀的chartjs-plugin-crosshair中复制到interpolate.js的。

请看看下面的可运行代码,看看它是如何工作的:

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>

最新更新