Reputation: 6656
I use vue-chartjs as a wrapper for chartjs. I had a simple line chart with random data but stuck on how to set fix value to be displayed on the chart's y-axis. Currently I have random data from 0-100. Now, what I want to achieve is just display 0, 50, 100
on the y-axis no matter what the random value is starts from 0-100
.
Sample Script
putData: function () {
this.datacollection = {
labels: ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'],
datasets: [{
lineTension: 0,
borderWidth: 1,
borderColor: '#F2A727',
pointBackgroundColor:[ '#fff', '#fff', '#fff', '#fff', '#fff', '#F2A727'],
backgroundColor: 'transparent',
data: [this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt()]
}]
}
},
getRandomInt: function () {
return Math.floor(Math.random() * (95)) + 5
}
Any help would be much appreciated.
Upvotes: 1
Views: 5579
Reputation: 3545
Above answer is correct. For those intereseted, I post code for latest version of Chart.js
Updated to Chart.js v3.2.0 (not backwards-compatible with v2.xx)
In order to avoid automatic scaling if your random data values are all in the middle range close to 50, do the following:
Add min: 0
and max: 100
, so you force chart to show exactly those 3 ticks including the 0, hence maxTicksLimit: 3
:
100
50
0
<script>
// ...
options: {
scales: {
y: {
min: 0,
max: 150,
ticks: {
stepSize: 50,
maxTicksLimit: 3
}
}
}
};
// ...
</script>
Source: https://www.chartjs.org/docs/latest/axes/#tick-configuration
(Be aware that in new versions v3.xx min: 0
and max: 100
are now located outside the ticks-object, whereas in v2.xx it used to be inside the ticks-object).
Upvotes: 2
Reputation: 32889
To achieve that, you need to set stepSize: 50
and maxTicksLimit: 3
for y-axis ticks, in your chart options :
scales: {
yAxes: [{
ticks: {
stepSize: 50,
maxTicksLimit: 3
}
}]
}
Upvotes: 5