我正在尝试从 chart.js
修改散点图的 X 轴
。为此,我只需按照 documentation 进行操作即可说。
但就我而言,我想做的是用一个单词替换实际值(数字)。问题是我不知道如何访问这些单词(它们位于一个数组中并且顺序正确)。
数组是这样的:
words = ['Apple','Orange','Banana', 'Pineapple', 'Strawberry', 'Lemon']
我的数据集是这样的:
datasets: [{
label: 'Dataset1',
borderColor: '#FF0000',
data: [{ x: 1, y: 88 }, { x: 2, y: 89 }, { x: 3, y: 86 }]
}, {
label: 'Dataset2',
borderColor: '#00FF00',
data: [{ x: 1, y: 88 }, { x: 2, y: 89 }, { x: 3, y: 86 }]
}]
xAxes 标签:
xAxes: [{
type: 'linear',
position: 'bottom',
ticks: {
callback: function(value, index, values) {
console.log(words[index]);
return '$' + value; //The $ is just to see some change
}
}
}]
我尝试使用索引值,但它只返回最后一个数据集索引值。另一种选择是尝试使用数组的第一个值,然后删除此值。
我该怎么做?
非常感谢。
最佳答案
我必须猜测数据的语义,但得出了以下可运行的代码片段。我希望这有帮助。
const words = ['Apple','Orange','Banana', 'Pineapple', 'Strawberry', 'Lemon'];
new Chart(document.getElementById("myChart"), {
"type": "scatter",
"data": {
datasets: [{
label: 'Dataset1',
borderColor: '#FF0000',
data: [{ x: 1, y: 88 }, { x: 2, y: 89 }, { x: 3, y: 86 }]
}, {
label: 'Dataset2',
borderColor: '#00FF00',
data: [{ x: 1, y: 65 }, { x: 2, y: 78 }, { x: 3, y: 33 }]
}]
},
"options": {
type: 'linear',
position: 'bottom',
scales: {
xAxes: [{
type: 'linear',
ticks: {
callback: (value, index, values) => words[index],
stepSize: 1
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="100"></canvas>
关于javascript - 修改chart js中的x轴标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59842146/