简体   繁体   中英

Chart.js time scale graph - xAxis labelling

I'm trying to set my own labels on the xAxis however I'm not sure how to do it using the example code I found.

I want it to look like this essentially: https://www.chartjs.org/samples/latest/scales/time/line.html

var result = [{ x: "00:01:53", y: "22" }, { x: "00:02:13", y: "45" }, { x: "00:02:43", y: "46" }, { x: "00:02:51", y: "51" }];
var result2 = [{ x: "00:01:52", y: "20" }, { x: "00:02:11", y: "42" }, { x: "00:02:41", y: "43" }, { x: "00:02:38", y: "50" }];

var labels = result.map(e => moment(e.x, 'h:mm:ss'));

var data = result.map(e => +e.y);
var data2 = result2.map(e => +e.y);

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: labels,
      datasets: [
          {
         label: 'g-force',
         data: data,
        borderColor: "#3e95cd",
         borderWidth: 1
      },
          {
         label: 'g-force',
         data: data2,
              borderColor: "#8e5ea2",
         borderWidth: 1
      }

      ],

   },
   options: {
      scales: {
         xAxes: [{
            type: 'time',
            time: {
               unit: 'second',
               displayFormats: {
                  second: 'h:mm:ss'
               }
            }
         }]
      },
   }
});

This seems to work. This code starts from today and adds in the next 10 days. You'll have to change date to whenever you want your start date to be as well as how many dates you need.

let labels = [];
var date = new Date();
var options = {
  month: "long",
  day: "numeric"
};

for (i = 0; i < 10; i++) {
    date.setDate(date.getDate() + i);
    labels.push(date.toLocaleDateString("en-US", options));
}


var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: labels,
      ...

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