How to change labels of LineChart in react-native-chart-kit

Viewed 5965

I drawed a graph in react native using sql server data and php backEnd ;

But I want to modify my label (value existing in x of graph)

export default class Home extends React.Component {
  constructor(props) {
      super(props);
      this.state = {
         isLoading: true,
         data: {
             labels: [],
             datasets: [
                 {
                     data: [],
                 }
             ]
         }
      }
  }
  componentDidMount() {
   this.GetData();
   }
  GetData = () => {
      const self = this;
      return fetch('http://192.168.1.5:80/graph.php')
      .then((response) => response.json())
      .then((responseJson) => {
        const dataClone = {...self.state.data}
        const values = responseJson.map(value => value.ChiffreAffaire);
        const label = responseJson.map(value => value.M500_NOM);

      dataClone.datasets[0].data = values;
      dataClone.labels= label;

        this.setState({
          isLoading: false,
          data: dataClone,
        });

      })
      .catch((error) =>{
        console.error(error);
      });
  }

  render() {
    const fill='rgb(134,65,244)'
    if(this.state.isLoading){
    return(
      <View style={{flex: 1, padding: 20}}>
          <ActivityIndicator/>
        </View>
    )
  }
      return (

        <View style={{flex: 1}}>

      <View style={{backgroundColor:'#58ACFA',flex:1,justifyContent: 'center'}}>
            <TouchableOpacity style={{marginTop:32,marginLeft:20}} onPress={this.props.navigation.openDrawer }>
            <FontAwesome5 name="bars" size={24} color="#161924" />
            </TouchableOpacity >
            </View>

            <ScrollView >
            <LineChart
            data={this.state.data}
            width={Dimensions.get("window").width*0.9}
            height={400}
            yAxisLabel={"DH"}
            chartConfig={chartConfig}
            bezier
            style={{
              marginTop:40,
              marginLeft:20,
              fontSize:1,
            }}
            />
            </ScrollView>

            </View>

As you see in this graph ,I should mention the names of Client but It's not lisible because it's it's condensed , If there is any option to mention them when I click on the button or to write it in vertical way ;

Please ,Any Idea ???

2 Answers

You can use verticalLabelRotation to rotate labels in x-axis.

In your code you can use like this

<LineChart
        verticalLabelRotation={110} //Degree to rotate
        data={this.state.data}
        width={Dimensions.get("window").width*0.9}
        height={400}
        yAxisLabel={"DH"}
        chartConfig={chartConfig}
        bezier
        style={{
          marginTop:40,
          marginLeft:20,
          fontSize:1,
        }}
       />

you can edit the labels to return empty strings for the labels you don't wish to appear. you just have to ensure that the data and label arrays are the same lengths. here is an example of code I made that does this. I made it so only certain times showed up on the label by mapping through the array and returning an empty string if it was a time I didn't want to show up, and returning the time formatted in a few different ways depending a switch statement. (eg. HH:MM, or MM/DD)

export const cleanChartData = (chartData: ChartData, days: number) => {
  const cleanedData = {
    data: [],
    labels: [],
  };
  switch (days) {
    case 1:
      cleanedData.data = chartData.bars.filter(bar => {
        const time = new Date(bar.t).toLocaleTimeString('en-US', {
          hour12: false,
        });
        if (time >= '09:30:00' && time <= '16:00:00') {
          return true;
        }
        return false;
      });
      cleanedData.labels = cleanedData.data.map(bar => {
        const timestamp = new Date(bar.t);
        const mins = ('0' + timestamp.getMinutes()).slice(-2);
        if (timestamp.getMinutes() % 60 === 0) {
          return `${
            timestamp.getHours() > 12
              ? timestamp.getHours() - 12
              : timestamp.getHours()
          }:${mins}`;
        } else {
          return '';
        }
      });
      break;
    case 7:
      cleanedData.data = chartData.bars.filter(bar => {
        const time = new Date(bar.t).toLocaleTimeString('en-US', {
          hour12: false,
        });
        if (time >= '09:30:00' && time <= '16:00:00') {
          return true;
        }
        return false;
      });
      cleanedData.labels = cleanedData.data.map(bar => {
        const timestamp = new Date(bar.t);
        const mins = ('0' + timestamp.getMinutes()).slice(-2);
        if (
          timestamp.getMinutes() % 60 === 0 &&
          timestamp.getHours() % 6 === 0
        ) {
          return `${timestamp.getDate()}`;
        } else {
          return '';
        }
      });
      break;
    case 30:
      cleanedData.data = chartData.bars;
      cleanedData.labels = chartData.bars.map(bar => {
        const timestamp = new Date(bar.t);
        const month = timestamp.getMonth();
        const date = timestamp.getDate();
        if (timestamp.getDay() === 5 && timestamp.getHours() > 12) {
          return `${month}/${date}`;
        } else {
          return '';
        }
      });
      break;
    case 90:
      cleanedData.data = chartData.bars;
      cleanedData.labels = chartData.bars.map(bar => {
        const timestamp = new Date(bar.t);
        const month = timestamp.getMonth();
        const date = timestamp.getDate();
        if (timestamp.getDay() === 5 && timestamp.getHours() > 12) {
          return `${month}/${date}`;
        } else {
          return '';
        }
      });
      break;
    default:
      break;
  }
  log.info(cleanedData);
  return cleanedData;
};

Related