【问题标题】:change date on x-axis dynamically动态更改 x 轴上的日期
【发布时间】:2017-07-26 08:18:25
【问题描述】:

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

【问题讨论】:

  • 到目前为止你做了什么?你能分享一些代码尝试吗?我认为您必须更好地详细说明您正在尝试做的事情。
  • 好吧,我开始写东西了,但我想也许有一个现成的 chart.js 和 moment.js 选项..

标签: javascript graph momentjs chart.js chart.js2


【解决方案1】:

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

您必须实现自己的 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();
});

【讨论】:

【解决方案2】:

你要找的是这个:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多