[Chartjs]-Chartjs โ€“ How to get last 7 days on x-axis labels?

4๐Ÿ‘

โœ…

You can instantiate a chart for the last seven days with the following code:

let start = new Date(),
  end = new Date();

start.setDate(start.getDate() - 7); // set to 'now' minus 7 days.
start.setHours(0, 0, 0, 0); // set to midnight.

new Chart(document.getElementById("chart"), {
  type: "line",
  options: {
    scales: {
      xAxes: [{
        type: "time",
        time: {
          min: start,
          max: end,
          unit: "day"
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<canvas id="chart"></canvas>

The date arithmetic works because of the Date object auto correcting itself when the value is invalid for the set month.

Youโ€™ll need to provide your values as x (or t) & y properties, as specified in the documentation.

0๐Ÿ‘

You have to put them on the axis yourself. See this.
Of course, you need to get the information on the y-axis from your backend. How you do this depends on how your data is structured

0๐Ÿ‘

You can get it with:

const dataArray = yourChart.data.datasets[0].data
console.log(dataArray.slice(Math.max(dataArray.length - 7, 1)))

Leave a comment