简体   繁体   中英

n3-charts dynamically changing x-axis label for date

I'm trying to create a label function that will dynamically change the x-axis label depending on the date range selected as the graph in this website .

To make things easier, the ticks in the x-axis is statically set to 12 instead of dynamically changing it depending on the date range, which I think could be rather difficult.

Say a date range of within 1 month will return the label as:

A day

6 PM - 9 PM - Sat 25 - 03 AM - 06 AM - 09 AM - 12 PM - 03 PM - 06 PM - 09 PM - Sun 26 - 03 AM

A week

Sun 10 - Mon 11 - Tue 12 - ... - Sat 16

A Month

27Mar - 29Tue - 31Apr- Fri - 03Apr - 05 Tue - 07 Thu 09 Sat...

Using the d3.time.format("%I:%M %p") as the labelFunction works, however it is not suitable to change the label dynamically. I also tried to create a separate functions formatDateAxis() to return the string depending on the startDate and endDate (in Unix epoch milliseconds) and return the format depending on the range, but fails returning only the format itself, eg %I %p.

  $scope.options = {
    axes: {
      x: {key: 'x', labelFunction: d3.time.format("%I:%M %p"), type: 'date', ticks: 12},
      y: {key: 'y1', type: 'linear', min: 20, max: 60, ticks: 5},
      y2: {key: 'y2', type: 'linear', min: 20, max: 60, ticks: 5}
    },
    series: [
      {y: 'value', color: '#0099FF', thickness: '2px', label: 'Temperature', dotSize: 2},
      {y: 'otherValue', axis: 'y2', color: '#6666FF', thinkness: '2px', visible: true, dotSize: 2, label: 'Humidity'}
    ],
    lineMode: 'linear',
    tension: 0.7,
    tooltip: {mode: 'scrubber', formatter: function(x, y, series) {return moment(x).fromNow() + ' : ' + y;}},
    drawLegend: true,
    drawDots: false,
    columnsHGap: 5
  }  

Function to format the x axis depending on the startDate and endDate of the selected data source. Referred from another stackoverflow post here .

var formatXAxes = function(value) {
  var dateFormat = "";
  if (endDateMillis - startDateMillis > 1468800000) {
    dateFormat = d3.time.format('%a %d');
  }

  else if (endDateMillis - startDateMillis > 172800000) {
    dateFormat = d3.time.format('%a %d');
  }

  else {
    dateFormat = d3.time.format('%I %p');
  }
  return dateFormat;
}

I would appreciate any helps to achieve this task to chart some historical sensor records for my home.

You can access the formatter by accessing the n3chart options javascript object say if you want to change the format of your x axis you can do:

$scope.options.axes.x.ticksFormat = '%X'

this will automatically update the ticksFormat and the n3chart will be updated in realtime to show the change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM