问题
I have charts where a user can input a different range of time spans in order to get a desired result set to graph. Depending on the range of the graph, the formatting of the times should be different. As an example, looking at a graph that's 10 minutes long, you'll probably see something along the lines of a time that's formatted HH:MM, but that won't make sense for a month long graph, where formatting would make more sense in the format of mm/dd.
I have the beginning timestamp (unix ts) and the ending timestamp (also unix ts) when a dataset is returned.
Does Chart.js have the tools to be able to help make smart decisions on formatting the time labels by converting the timestamps I have above? Do I need to write a callback with a custom algorithm that determines the timestamp of the graph and label manually?
There would need to be some code to cover a lot of the use cases if a manual algorithm is required that looks something along the lines of:
if (timespan > 86400 * 30)
{
// create format code for month
}
else if (timespan > 86400 * 5)
{
// weekly format
}
else if ( ... ) {}
Is there a better way about this with Chart.js?
回答1:
From the Chart.js time axis documentation:
When building its ticks, it will automatically calculate the most comfortable unit base on the size of the scale.
This appears to work well as shown in the two charts below, the first with a range of 10 minutes and the second with a range of 10 days:
let now = (new Date()).getTime(),
minutes = [],
days = [],
options = {
scales: {
xAxes: [{
type: 'time'
}]
}
};
for (let i = 0; i < 10; i++) {
minutes.push({
x: now + (60000 * i),
y: 10
});
days.push({
x: now + (86400000 * i),
y: 10
});
}
new Chart(document.getElementById('canvas1'), {
type: 'line',
data: {
datasets: [{
data: minutes
}]
},
options: options
});
new Chart(document.getElementById('canvas2'), {
type: 'line',
data: {
datasets: [{
data: days
}]
},
options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.min.js"></script>
<canvas id="canvas1"></canvas>
<canvas id="canvas2"></canvas>
You can pass in display formats for the various units (minute, day, month, etc) to automatically get the scaling and formatting you want.
来源:https://stackoverflow.com/questions/54299812/chart-js-v2-formatting-time-labels