[Chartjs]-Change date on x-axis dynamically

1👍

Per the chart.js API, the Time Scale is what you will want to use. However, the scale will not automatically adjust the display format based upon the magnitude of the span of dates in your dataset.

You will have to implement your own javascript function that will change the scale options for what you want based upon the selected data. This might sound challenging, but if you think about it its really not.

In fact, since you will be providing your users with a way to filter data, you will already have to implement a similar function that will change the underlying data in the chart (after a user sets a filter) and then re-render the chart (achieved by using the .update() prototype method).

In this same function, implement your logic to determine the appropriate time scale display format (based upon the span of your data) and just update the chart scale options as well (before you call .update()). Here is an example below.

Assuming you have some sort of date range select box in your HTML with a class of .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();
});

1👍

What you are looking for is this:

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

Presenting that you want data for just a day (24 hours) so go by hours as given in this above example.

More info:
https://www.chartjs.org/docs/latest/axes/cartesian/time.html

Leave a comment