Chartjs-Charts.js line chart: Show the most recent date on x-axis when setting ticks.maxTicksLimit

1👍

This could be solved by somehow implement your own ticks.maxTicksLimit on the xAxis. You would have to proceed as follows.

  1. Define the xAxis as a time cartesian axis that accepts the data as an array of data points using an object containing x and y properties.
  2. Generate a labels array out of the years contained in your data. This array should contain the starting year and end year together with a number of equally spread years between both (see function createLabels in the code snippet below).
  3. Tell Chart.js to generate ticks on the xAxis from given labels by defining tick.sources: 'labels'.
const data = [];
for (let year = new Date().getFullYear() - 29; year <= new Date().getFullYear(); year++) {
  data.push({
    x: year.toString(),
    y: Math.floor((Math.random() * 6) + 1)
  })
}

const maxTicksLimit = 6;
function createLabels() {
  const years = data.map(o => Number(o.x));
  const startTime = years[0];
  const endTime = years[years.length - 1];
  const tickGap = (endTime - startTime) / (maxTicksLimit - 1);
  const labels = [startTime];
  for (let i = 1; i < maxTicksLimit - 1; i++) {
    labels.push(Math.round(startTime + i * tickGap));
  }
  labels.push(endTime);
  return labels.map(l => l.toString());
}

new Chart('myChart', {
  type: 'line',
  data: {
    labels: createLabels(),
    datasets: [{
      label: 'Demo',
      fill: false,
      data: data,
      borderColor: 'blue'
    }]
  },
  options: {
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          parser: 'YYYY',
          unit: 'year'
        },
        ticks: {
          source: 'labels'
        }      
      }],
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="80"></canvas>

Leave a comment