首页 文章

动态更改x轴上的日期

提问于
浏览
2

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

2 回答

  • 0

    根据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();
    });
    
  • 0

    你在寻找的是:

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

    假设您只需要一天(24小时)的数据,那么请按上面示例中给出的小时数 .

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

相关问题