Reputation: 508
With Chart.js, is there a way of setting a dynamic maximum y-axis value?
I have a chart for which the absolute maximum for a value is always 999. If the values are low (50, 100 or 200 for instance), the y-axis auto-scales (the maximum tick would be respectively 60, 110 or 210 for instance) as expected.
However, if one of the data points is 999, the y axis maximum becomes 1000. Is there any way to set 999 as the y-axis maximum without forcing this maximum to be 999 if I only have low values in my chart? I have tried using max
of suggestedMax
in the options unsuccessfully.
Upvotes: 0
Views: 5914
Reputation: 26150
The easiest would be to define the data
in a variable outside of the chart configuration and then use Math.max()
to define scales.y.max
.
scales: {
y: {
max: Math.max(...data)
},
Please take a look at the following runnable code derived from the Chart.js documentation and see how it works.
let data = [650, 595, 999, 815, 56, 155, 440];
new Chart('myChart', {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First Dataset',
data: data,
fill: false,
borderColor: 'rgb(75, 192, 192)',
lineTension: 0.1
}]
},
options: {
responsive: true,
plugins: {
tooltip: {
mode: 'index',
intersect: false,
}
},
scales: {
y: {
title: {
display: true,
text: 'Value'
},
max: Math.max(...data)
},
x: {
title: {
display: true,
text: 'Month'
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.0-beta.13/chart.js"></script>
<canvas id="myChart" height="100"></canvas>
Upvotes: 3