且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在本地图表工具包中的barChart中导入Y标签

更新时间:2023-11-14 19:17:58

From looking at the source code for the BarChart it seems the formatYLabel function should be declared as a property inside chartConfig instead of being set as a prop, as is the case with the LineChart.

Another problem you need to be aware of is that this library derives the minimum and maximum y-axis value based on the data array you pass in. The problem with this is that even though you might set your labels to be [80, 90, 100], the values won't necessarily correspond.

Said in another way: If your minimum value label is a different value from the minimum value in your data array the labels won't match up entirely.

Even though taking the minimum value from the data array is the default, there is a fromZero prop you can set to true which makes the y-axis start value 0.

We can take advantage of this by doing something like this:

const minValue = 80;

function* yLabel() {
  yield* [minValue, 90, 100];
}

const datapoints = [89, 88, 96, 97, 94, 91, 88].map(
  (datapoint) => datapoint - minValue - 1,
);

const data = {
  labels: ['Sat', 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
  datasets: [
    {
      data: datapoints,
    },
  ],
};

const App = () => {
  const screenWidth = Dimensions.get('window').width;
  const yLabelIterator = yLabel();

  return (
    <View>
      <BarChart
        style={{
          marginVertical: 8,
          borderRadius: 16,
        }}
        data={data}
        segments={2}
        width={screenWidth}
        height={220}
        verticalLabelRotation={0}
        fromZero={true}
        chartConfig={{
          backgroundColor: '#e26a00',
          backgroundGradientFrom: '#fb8c00',
          backgroundGradientTo: '#ffa726',
          decimalPlaces: 0, // optional, defaults to 2dp
          color: (opacity = 3) => `rgba(200, 255, 255, ${opacity})`,
          labelColor: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
          style: {
            borderRadius: 30,
          },
          formatYLabel: () => yLabelIterator.next().value,
          data: data.datasets,
          propsForDots: {
            r: '6',
            strokeWidth: '2',
            stroke: '#ffa726',
          },
        }}
      />
    </View>
  );
};

export default App;

I've also changed the amount of segments from 3 to 2. The segments are the spaces between the labels, so if you want 3 labels you want 2 segments.

Result:


So the idea of subtracting minValue - 1 from each datapoint is to say: What is the difference between my minimum value label 80 and 0 (The start value when fromZero is set to true). Then subtract another 1 since 0 itself is also part of the range. This gives us a value that signifies how much each value in the data array should be corrected in order to display the bars on the correct height according to the labels we've passed.

This approach assumes your max value label will be more than the max value in the data array.