Невозможно отобразить правильное время на временной шкале chart.js. - PullRequest
0 голосов
/ 21 декабря 2018

Я пытаюсь создать диаграмму, используя библиотеку Chart.js.Ось X должна быть временной шкалой с таким форматом времени: DD-MM-YYYY HH:MM:SS, но на графике она дает неправильные даты, и даже мои данные не отображаются должным образом.Если я удаляю HH:MM:SS часть, остальное работает нормально.В чем проблема?Как я могу отобразить время в DD-MM-YYYY HH:MM:SS fromat?

Вот моя скрипка: http://jsfiddle.net/vaxobasilidze/ak1vmj9q/

function factorData(data) {
  let _data = data.map((e, i, a) => {
    let prev = a[i - 1];
    let next = a[i + 1];
    if (e === prev && e === next) return '' + e;
    return e;
  }).map(e => typeof e === 'string' ? null : e);
  return _data;
}

var ctx = document.getElementById('chart').getContext('2d');

var gradient1 = ctx.createLinearGradient(0, 0, 0, 400);
gradient1.addColorStop(0, 'rgba(14, 22, 38, 1)');
gradient1.addColorStop(1, 'rgba(1, 103, 147, 0.7)');
/***************/

var datas = [];
datas.push({x: "01-04-2001 10:05:46", y: 175});
datas.push({x: "01-10-2002 10:15:46", y: 140});
datas.push({x: "01-07-2003 11:47:26", y: 98});
datas.push({x: "01-10-2003 01:07:42", y: 130});
datas.push({x: "01-09-2006 06:55:46", y: 164});
datas.push({x: "01-04-2013 10:22:35", y: 178});
datas.push({x: "01-10-2015 10:05:46", y: 118});
datas.push({x: "01-10-2018 10:05:46", y: 158});


var timeFormat = "DD-MM-YYYY HH:MM:SS";

var options = {
  type: 'line',
  data: {
    datasets: [{
      fillColor: gradient1,
      backgroundColor: gradient1,
      borderColor: gradient1,
      fill: 'origin',
      strokeColor: gradient1,
      pointBackgroundColor: "#00b2ff",
      pointRadius: 2,
      pointBorderWidth: 0,
      pointHoverRadius: 3,
      pointHoverBackgroundColor: "rgba(0, 178, 255, 1)",
      data: datas,
      steppedLine: true,
      spanGaps: true
    }, ]
  },
  options: {
    responsive: true,
    maintainAspectRatio: false,
    datasetStrokeWidth: 1,
    pointDotRadius: 3,
    pointDotStrokeWidth: 1,
    pointHitDetectionRadius: 1,
    tooltipFillColor: "rgba(120,0,0,0.8)",
    tooltipFontStyle: "bold",
    animation: false,
    scaleFontColor: "#ffffff",
    scaleFontStyle: "bold",
    scales: {
      xAxes: [{
        type: "time",
        time: {
          format: timeFormat,
          tooltipFormat: 'll',
          min: new Date(2001, 1, 4, 1, 0, 0, 0),
        },
        ticks: {
          maxTicksLimit: 21,
          minRotation: 90,
          fontColor: '#ffffff'
        },

        gridLines: {
          color: "#444444"
        }
      }],
      yAxes: [{
        ticks: {
          fontColor: '#ffffff'
        },
        gridLines: {
          color: "#444444"
        },
      }]
    }
  },
}

var myLineChart = new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<canvas id="chart" width="800" height="400" style="background: #202020"></canvas>

1 Ответ

0 голосов
/ 21 декабря 2018

Я полагаю, вы ищете DD-MM-YYYY HH:mm:ss См. moment.js для списка токенов допустимого формата (chart.js использует те же форматы, которые указаны здесь ).

ММ - на месяцы (поскольку вы правильно используете в разделе DD-MM-YYYY, а СС - на доли секунды. Я не думаю, что вы хотите, чтобы какой-либо из них отображал время (может быть неправильно с этим надоли секунды, но определенно не месяцы, а минуты)

Если вы хотите, чтобы на ваших этикетках также было время, тогда вы можете использовать:

`type: "time",
time: {
   displayFormats:{ timeFormat },
   min: new Date(2001, 1, 4, 1, 0, 0, 0),
},`

Оба эти решениякомбинированные доходности на следующем графике:

function factorData(data) {
  let _data = data.map((e, i, a) => {
    let prev = a[i - 1];
    let next = a[i + 1];
    if (e === prev && e === next) return '' + e;
    return e;
  }).map(e => typeof e === 'string' ? null : e);
  return _data;
}

var ctx = document.getElementById('chart').getContext('2d');

var gradient1 = ctx.createLinearGradient(0, 0, 0, 400);
gradient1.addColorStop(0, 'rgba(14, 22, 38, 1)');
gradient1.addColorStop(1, 'rgba(1, 103, 147, 0.7)');
/***************/

/* var datas = [];
var labelss = [];
var quantity = 50;
for (var i = 0; i < quantity; i++) {
  var test = Math.floor((Math.random() * 100) + 1);
  datas.push(test);
  labelss.push(i);
} */

var datas = [];
datas.push({x: "01-04-2001 10:05:46", y: 175});
datas.push({x: "01-10-2002 10:15:46", y: 140});
datas.push({x: "01-07-2003 11:47:26", y: 98});
datas.push({x: "01-10-2003 01:07:42", y: 130});
datas.push({x: "01-09-2006 06:55:46", y: 164});
datas.push({x: "01-04-2013 10:22:35", y: 178});
datas.push({x: "01-10-2015 10:05:46", y: 118});
datas.push({x: "01-10-2018 10:05:46", y: 158});


var timeFormat = "DD-MM-YYYY HH:mm:ss";

var options = {
  type: 'line',
  data: {
    //labels: labelss,
    datasets: [{
      fillColor: gradient1,
      backgroundColor: gradient1,
      borderColor: gradient1,
      fill: 'origin',
      strokeColor: gradient1,
      pointBackgroundColor: "#00b2ff",
      pointRadius: 2,
      pointBorderWidth: 0,
      pointHoverRadius: 3,
      pointHoverBackgroundColor: "rgba(0, 178, 255, 1)",
      data: datas,
      steppedLine: true,
      spanGaps: true
    }, ]
  },
  options: {
    responsive: true,
    maintainAspectRatio: false,
    datasetStrokeWidth: 1,
    pointDotRadius: 3,
    pointDotStrokeWidth: 1,
    pointHitDetectionRadius: 1,
    tooltipFillColor: "rgba(120,0,0,0.8)",
    tooltipFontStyle: "bold",
    animation: false,
    scaleFontColor: "#ffffff",
    scaleFontStyle: "bold",
    scales: {
      xAxes: [{
        type: "time",
        time: {
          displayFormats:{ timeFormat },
          min: new Date(2001, 1, 4, 1, 0, 0, 0)
        },
        ticks: {
          maxTicksLimit: 21,
          minRotation: 90,
          fontColor: '#ffffff'
        },

        gridLines: {
          color: "#444444"
        }
      }],
      yAxes: [{
        ticks: {
          fontColor: '#ffffff'
        },
        gridLines: {
          color: "#444444"
        },
      }]
    }
  },
}

var myLineChart = new Chart(ctx, options);
...