// initial chart definition
var chart = new Chart($('#myChart'), {
type: 'line',
data: {
labels: [/* chart labels */],
datasets: [{
data: { /* chart data */},
}]
},
options: { /* options...including time scale options */}
});
// change handler on the date filter drop down which changes the chart data and time scale options
$( ".date-filter" ).change(function() {
var selectedRange = $(this).val();
var parsedStartDate = // use selectedRange to parse start date
var parsedEndDate = // use selectedRange to parse end date
var dayMagnitude = // use moment.js to calculate difference in start/end in days
if (daysMagnitude < 30) {
// configure time scale displayFormat in terms of days
} else if (daysMagnitude < 90) {
// configure time scale displayFormat in terms of months
} else if (daysMagnitude < 180) {
// configure time scale displayFormat in terms of quarters
}
// ...
// update the underlying chart data by accessing the underlying dataset that you are modifying
chart.data.datasets[0].data = // new data object based on the filter criteria
// update the time scale options
chart.options.scales.yAxes = // updated time scale options
// re-render your chart
chart.update();
});
2 回答
根据chart.js API,Time Scale是您想要使用的 . 但是,比例不会根据数据集中日期范围的大小自动调整显示格式 .
您必须实现自己的javascript函数,该函数将根据所选数据更改所需的缩放选项 . 这可能听起来很有挑战性,但如果你考虑它真的不是 .
实际上,由于您将为用户提供过滤数据的方法,因此您必须实现类似的功能,该功能将更改图表中的基础数据(在用户设置过滤器之后),然后重新呈现图表(通过使用.update()原型方法实现) .
在同一个函数中,实现您的逻辑以确定适当的时间刻度显示格式(基于数据范围),并且只需更新图表缩放选项(在调用
.update()
之前) . 以下是一个例子 .假设您的HTML中有一些日期范围选择框,其类为
.date-filter
...你在寻找的是:
假设您只需要一天(24小时)的数据,那么请按上面示例中给出的小时数 .
更多信息:
https://www.chartjs.org/docs/latest/axes/cartesian/time.html