2017-03-06 92 views
0

我有一个图表,我的x轴是一个时间轴,我需要根据我的数据动态更改时间轴。例如: 例如: 如果日期范围(在我的数据中)很大,我需要我的坐标轴来显示月份,如果范围小于日期。 我试图让它更清晰: 我有一个日期范围:'09/07/2016' - '09/02/2016' - 我的轴需要根据天显示我的数据。 但: 如果我的范围是:'09/07/2016' - '09/02/2017'那么我的轴需要显示几个月或四分之一,因为这两个日期之间的差距更大。 这是可能的和如何?在x轴上动态更改日期

+0

什么你试过这么远吗?你能分享一些代码尝试吗?我认为你必须更好地详细说明你正在尝试做什么。 – VincenzoC

+0

以及我开始写东西,但我想也许有一个现成的选项chart.js&moment.js .. – Damkulul

回答

0

根据chart.js API,Time Scale是您想要使用的。但是,缩放不会根据数据集中日期范围的大小自动调整显示格式。

你将不得不实现你自己的javascript函数,它将基于选定的数据改变你想要的尺度选项。这听起来很有挑战性,但如果你仔细想想它其实并非如此。实际上,由于您将为用户提供过滤数据的方法,因此您必须实现一个类似的功能,该功能将更改图表中的基础数据(在用户设置过滤器之后),然后重新 - 绘制图表(通过使用.update()原型方法实现)。

在这个相同的功能中,实现您的逻辑来确定合适的时间尺度显示格式(基于您的数据跨度),并更新图表刻度选项(在您致电.update()之前)。下面是一个例子。

假设你有一个类的.date-filter你的HTML某种日期范围选择框......

// 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(); 
});