How to change the Y-axis values from numbers to strings in react native chart kit

5.1k Views Asked by At

I'm using react-native-chart-kit to display and am trying to change the y-axis (see screen shot below). I tried filling the yLabels property with an array of strings. But that didn't work. Any help would be appreciated!

enter image description here

1

There are 1 best solutions below

0
On

You can use the formatYLabel prop for this (https://github.com/indiespirit/react-native-chart-kit#line-chart):

/*
 * Generator helper function that allows us to
 * cleanly return a label from an array
 * of labels for each segment of the y-axis
 */
function* yLabel() {
  yield* ['None', 'Low', 'Med', 'High'];
}

function App() {
  // Instantiate the iterator
  const yLabelIterator = yLabel();

  return (
    <View>
      <LineChart
        data={{
          labels: ['Mo', 'Tu', 'We', 'Fr', 'Sa', 'Su'],
          datasets: [
            {
              data: [3, 2, 1, 4, 4],
            },
            {
              data: [5, 1, 3, 2],
            },
          ],
        }}
        segments={3}
        width={320}
        height={200}
        formatYLabel={() => yLabelIterator.next().value}
        chartConfig={{
          backgroundColor: 'white',
          backgroundGradientFrom: 'grey',
          backgroundGradientTo: 'grey',
          color: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
          labelColor: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
        }}
      />
    </View>
  );
}

export default App;

If you want to display 4 y-axis labels you need to set the segments prop of the LineChart to 3.

If you want to learn more about yield in Javascript you can read this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield*.