'How do I force Chart.js axes min and max with react-chartjs-2?
I'm trying to create a simple line chart with react-chartjs-2, and when I try to set the min/max values for the x- and y-axes, the values won't take.
I've tried all the following for options, and none of them are enforcing my specified mins and maxes:
1st attempt:
{
scales: {
x: {
max: 1000,
min: 0
},
y: {
max: 8,
min: -3
}
}
}
2nd attempt:
{
scales: {
x: {
ticks: {
max: 1000,
min: 0
}
},
y: {
ticks: {
max: 8,
min: -3
}
}
}
}
3rd attempt:
{
scales: {
x: {
suggestedMax: 1000,
suggestedMin: 0
},
y: {
suggestedMax: 8,
suggestedMin: -3
}
}
}
None of those seem to work though. What am I doing wrong / missing? Thank you.
As a side note, I find the Chart.js docs very confusing, and it's really hard to find valid examples online, especially since v1 and v2 of Chart.js seem to be fundamentally different.
Solution 1:[1]
Ugh! So frustrating, but I finally found the answer. The following worked for me:
{
scales: {
xAxes: [{
ticks: {
beginAtZero: true,
max: 1000,
min: 0
}
}],
yAxes: [{
ticks: {
beginAtZero: false,
max: 8,
min: -3
}
}]
}
}
Solution 2:[2]
For the current version of react-chartjs-2 (3/13/2022) the code below worked for me but the answer by HartleySan didn't change the output.
I'm using Nextjs with
chart.js: 3.7.1,
react-chartjs-2: 4.0.1,
<Line
datasetIdKey="id"
data={data}
options={{
scales: {
yAxis: {
min: 0,
max: 100,
},
....
},
}}
/>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | HartleySan |
| Solution 2 | YSLdev |
