[Chartjs]-How to add new x axis in chart JS?

1👍

You can define an additional x-axis that mainly contains an afterBuildTicks callback function as follows:

 {
   afterBuildTicks: scale => scale.ticks = ['A', 'B', 'C', 'D'],
   gridLines: {
     drawOnChartArea: false
   }
 }

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

const data = [];
let date = Date.parse('2020-01-01');
for (let day = 1; day <= 20; day++) {
  date = new Date(date);
  date.setDate(day);
  data.push({
    x: date,
    y: Math.floor((Math.random() * 6) + 1)
  })
};

new Chart('myChart', {
  type: 'line',
  data: {
    datasets: [{
      label: 'My Dataset',
      fill: false,
      data: data,
      borderColor: 'blue'
    }]
  },
  options: {
    scales: {
      xAxes: [{
          type: 'time',
          time: {
            unit: 'day'
          }
        },
        {
          afterBuildTicks: scale => scale.ticks = ['A', 'B', 'C', 'D'],
          gridLines: {
            drawOnChartArea: false
          }
        }
      ],
      yAxes: [{
        ticks: {
          beginAtZero: true,
          stepSize: 1
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Leave a comment