问题
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