A workaround is to do the following things:
- Use the
fromZero
prop on the chart;
- Use a generator function that represents your custom y-axis label values;
- Pass the results the label generator function gives to the
formatYLabel
prop;
- Adjust your data: Subtract your desired minimum label value from each number in your data set.
Example of the approach given above:
const minValue = 5;
const maxValue = 90;
function* yLabel() {
yield* [minValue, '', maxValue];
}
const d = [10, 5, 90, 30, 20, 10, 80];
const datapoints = d.map((datapoint) => datapoint - minValue - 1);
const data = {
labels: ['Sat', 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
datasets: [
{
data: datapoints,
},
],
};
const CustomChart = () => {
const screenWidth = Dimensions.get('window').width;
const yLabelIterator = yLabel();
return (
<View>
<LineChart
data={data}
segments={2}
width={screenWidth}
height={220}
bezier
fromZero
chartConfig={{
color: (opacity = 3) => `rgba(200, 255, 255, ${opacity})`,
data: data.datasets,
}}
formatYLabel={() => yLabelIterator.next().value}
/>
</View>
);
};
Subtracting 1
of each element in the data set is done because 0
is inclusive in the range when fromZero
is set.
Also be aware that the number of segments
of the chart is important here. If you want to have 3
labels, you should have 2
segments.
Having 2
labels, as in the example above, is the exception to the rule. Having 2
labels and 1
segment doesn't work. The workaround shown in the example is to have 3
labels and 2
segments, but to make the middle label an empty string.
A caveat with the approach as a whole is that you can't have a value in your data array that is higher than your maximum label value.