[Chartjs]-ChartJS dynamic label

1👍

You can define a xAxes.ticks.callback function. It should return the label when a corresponding data value exists, null otherwise.

xAxes: [{
  ticks: {
    callback: (v, i) => i + 1 <= trainingData.length ? v : null 
  }
}]     

Please take a look at the following runnable code and see how it works.

const trainingData =  [0.68, 0.9];
const validationData = [0.57, 0.97];

new Chart('line-chart', {
  type: 'line',
  data: {
    labels: [0, 1, 2, 3, 4],
    datasets: [{
        label: 'Training',
        data: trainingData,
        fill: false,
        borderColor: 'rgb(0, 119, 182)',
        backgroundColor: 'rgb(0, 119, 182)',
        lineTension: 0,
      },
      {
        label: 'Validation',
        data: validationData,
        fill: false,
        borderColor: 'rgb(0, 180, 216)',
        backgroundColor: 'rgb(0, 180, 216)',
        lineTension: 0,
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          min: 0,
          max: 1          
        }
      }],
      xAxes: [{
        ticks: {
          callback: (v, i) => i + 1 <= trainingData.length ? v : null 
        }
      }]      
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="line-chart" height="90"></canvas>

Leave a comment