[Chartjs]-ChartJS – Scale x axis labels from single days to multiple months

1πŸ‘

βœ…

It should work as expected if you make the entry inside displayFormats the same as unit.

displayFormats: {
  month: 'MM/YY'
}

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

const now = new Date();
const data = new Array(100).fill().map((v, i) => {
  const date = new Date();
  date.setDate(now.getDate() + i);
  return { x: date.toISOString().substring(0, 10), y: Math.floor(Math.random() * 10) };
});

new Chart('chart', {
  type: 'line',
  data: {
    datasets: [{
        label: "Data",        
        borderColor: "rgb(255, 0, 0)",
        data: data,
        fill: false
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],
      xAxes: [{
        type: 'time',
        time: {
          parser: 'YYYY-MM-DD',
          unit: 'month',
          displayFormats: {
             month: 'MM/YY'
          },
          tooltipFormat: 'DD/MM/YY'
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.js"></script> 
<canvas id="chart" height="90"></canvas>

Leave a comment