3

我有一个图表,我的 x 轴是一个时间线,我需要我的时间线根据我的数据动态变化。 例如: 如果日期范围(在我的数据中)很大,我需要我的轴显示月份,如果范围很小,那么天。我会尽量让它更清楚:我有一个日期范围:'09/07/2016' - '09/02/2016'-我的轴需要根据天显示我的数据。但是:如果我的范围是:'09/07/2016' - '09/02/2017'那么我的轴需要显示月份或季度,因为这两个日期之间的差距更大。有可能吗?怎么做?

4

2 回答 2

1

您正在寻找的是:

chart.options.scales.xAxes[0].time.unit = 'hour';
chart.update();

表示您只需要一天(24 小时)的数据,因此按上述示例中给出的小时数计算。

更多信息:
https ://www.chartjs.org/docs/latest/axes/cartesian/time.html

于 2018-08-16T16:05:32.800 回答
1

根据 chart.js API,时间刻度是您想要使用的。但是,比例不会根据数据集中日期跨度的大小自动调整显示格式。

您将必须实现自己的 javascript 函数,该函数将根据所选数据更改您想要的比例选项。这听起来可能很有挑战性,但如果你仔细想想,它真的不是。

事实上,由于您将为您的用户提供一种过滤数据的方法,因此您已经必须实现一个类似的功能,该功能将更改图表中的基础数据(在用户设置过滤器之后),然后重新渲染图表(通过使用.update()原型方法实现)。

在同一个函数中,实现您的逻辑以确定适当的时间刻度显示格式(基于数据的跨度),并且也只需更新图表刻度选项(在调用之前.update())。下面是一个例子。

假设您的 HTML 中有某种日期范围选择框,其类别为.date-filter...

// 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();
});
于 2017-03-06T16:28:33.120 回答