Home > Blockchain >  ChartJS - Scale x axis labels from single days to multiple months
ChartJS - Scale x axis labels from single days to multiple months

Time:02-21

I want to create a line chart which has multiple single days as labels on the x axis. This actually works just fine. I am passing it this javascript array for the x_axis(example):

['2019-01-02', '2019-01-03', '2019-01-04', '2019-01-07', '2019-01-08', '2019-01-09', '2019-01-10', '2019-01-11', '2019-01-14', '2019-01-15', '2019-01-16']

The problem is, the chart can have 50 different x axis points and so it doesn't make sense to display all those at the same time because it over populates the x axis.

I would like to instead scale that so that it only uses the months on the x axis. I have been reading that I have to set up the xAxis with a scale, but I have tried various things and it doesn't seem to be working.

This is an example attempt I made that fails:

  options: {
      scales: {
        xAxis: [{
          type: 'time',
          position: 'bottom',
          time: {
            parser: 'YYYY-MM-DD',
            displayFormats: {'day': 'MM/YY'},
            tooltipFormat: 'DD/MM/YY',
            unit: 'month',
          }
        }]
      },  

Can anyone please give a pointer on how to do that? Thanks!

CodePudding user response:

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>

  • Related