Ghatzi
Ghatzi

Reputation: 597

ChartJS dynamic label

I'm trying to dynamically add a label to my line chart depending on the number of points coming back from the database. I have a table which, once the user clicks on a particular row, updates the chart. The number of point can vary. i.e chart 1 has 2 points & chart 2 has 5 points. I need to count the number of points and display the bottom label in a sequential number order. i.e 0, 1 for chart 1 and 0, 1, 2, 3, 4 for chart 2. The image below shows what I want to avoid happening. 2, 3 & 4 should not be showing in chart 1 but showing in chart 2.

enter image description here

enter image description here

I've hard coded the label data for this example [0, 1, 2, 3, 4]. xAxisValue.length brings back the number of points each chart displays. Appreciate any help.

data={{
              labels: [0, 1, 2, 3, 4],
              datasets: [
                {
                  label: 'Training',
                  data: yAxisValue,
                  fill: false,
                  borderColor: 'rgb(0, 119, 182)',
                  backgroundColor: 'rgb(0, 119, 182)',
                  lineTension: 0,
                },
                {
                  label: 'Validation',
                  data: xAxisValue,
                  fill: false,
                  borderColor: 'rgb(0, 180, 216)',
                  backgroundColor: 'rgb(0, 180, 216)',
                  lineTension: 0,
                },
              ],
            }}

Upvotes: 1

Views: 4942

Answers (1)

uminder
uminder

Reputation: 26150

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>

Upvotes: 1

Related Questions