Reputation: 1353
I'm trying to modify the X-axis
of my scatter graph from chart.js
. To do this, I just have to do as the documentation says.
But in my case, what I want to do, is replace the actual value (a number) with a word. The problem is that I don't know how to access to that words (they are in an array and they are in the correct order).
The array is like this:
words = ['Apple','Orange','Banana', 'Pineapple', 'Strawberry', 'Lemon']
And my dataset is like:
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 label:
xAxes: [{
type: 'linear',
position: 'bottom',
ticks: {
callback: function(value, index, values) {
console.log(words[index]);
return '$' + value; //The $ is just to see some change
}
}
}]
I tried to use the index value, but it just return the last dataset index value. Another option is try to use the first value of the array
and the delete this one just after.
How can I do it?
Thank you very much.
Upvotes: 0
Views: 1396
Reputation: 26190
I had to guess the semantics of your data but came up with following runnable code snippet. I hope this helps.
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>
Upvotes: 1