Chartjs - How to get last 7 days on x-axis labels?

旧街凉风 提交于 2021-02-07 10:31:01

问题


I am trying to get the last seven days on the x-axis of my line-chart (using chartjs). What is the best way to do this?

Thanks


回答1:


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.




回答2:


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




回答3:


You can get it with:

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


来源:https://stackoverflow.com/questions/58266605/chartjs-how-to-get-last-7-days-on-x-axis-labels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!