我想做的是获取 x 轴的位置,但我发现除非 x 轴具有完全相同的值,否则我无法获取它。但对于 y 轴,只要该值在 y 轴范围内,我就可以获得该值的位置。
有没有办法获取 x 轴上的值的坐标? X 轴的标签是数字,每个标签与下一个标签之间的步长相等。
我当前的代码是这样的。
<script>
import { Line } from 'vue-chartjs'
export default {
extends: Line,
data() {
return {
chartdata: {
labels: [
10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
],
datasets: [
{
label: '',
data: [
34, 56, 78, 12, 45, 67, 12, 89, 93, 43,
],
type: 'line',
borderColor: 'red',
fill: false,
lineTension: 0,
}
],
},
options: {
responsive: true,
scales: {
xAxes: [{
scaleLabel: {
display: true,
labelString: 'x',
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 10,
suggestedMax: 100,
},
scaleLabel: {
display: true,
labelString: 'y',
}
}],
}
}
}
},
mounted() {
this.addPlugin({
beforeDraw: (chart) => {
console.log(chart.scales['y-axis-0'].getPixelForValue(23.56)); // Can get a coordinate in canvas
console.log(chart.scales['x-axis-0'].getPixelForValue(36.98)); // The coordinate I get is out of canvas
console.log(chart.scales['x-axis-0'].getPixelForValue(40)); // Can get a coordinate in canvas because label has the same value (40)
}
});
this.renderChart(this.chartdata, this.options);
}
}
</script>
最佳答案
当data
是数字数组时,x轴通常是category 。这些点使用其在数组中的位置放置在轴上,该位置还应与 labels
中的值匹配。
Yo需要将x轴更改为linear输入以便从函数 getPixelForValue
获取正确的值。
- 不要定义
标签
- 将数据定义为 points 的数组使用分别包含
x
和y
属性的对象。 - 将
type: 'linear'
添加到xAxes
选项
请查看修改后的代码并了解其工作原理。
new Chart("chart", {
type: 'line',
plugins: [{
beforeDraw: (chart) => {
console.log(chart.scales['y-axis-0'].getPixelForValue(23.56));
console.log(chart.scales['x-axis-0'].getPixelForValue(36.98));
console.log(chart.scales['x-axis-0'].getPixelForValue(40));
}
}],
data: {
datasets: [{
label: '',
data: [
{ x: 10, y:34 },
{ x: 20, y:56 },
{ x: 30, y:78 },
{ x: 40, y:12 },
{ x: 50, y:45 },
{ x: 60, y:67 },
{ x: 70, y:12 },
{ x: 80, y:89 },
{ x: 90, y:93 },
{ x: 100, y:43 }],
type: 'line',
borderColor: 'red',
fill: false,
lineTension: 0,
}],
},
options: {
responsive: true,
scales: {
xAxes: [{
type: 'linear',
scaleLabel: {
display: true,
labelString: 'x',
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 10,
suggestedMax: 100,
},
scaleLabel: {
display: true,
labelString: 'y',
}
}],
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="chart" height="200"></canvas>
关于javascript - Chart.js:无法获取 x 轴值的坐标,除非 x 轴具有完全相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65317576/