Метки X-осей не соответствуют данным - PullRequest
0 голосов
/ 14 апреля 2020

Проблема в том, что: у меня есть данные во временном диапазоне каждые 15 минут. Начиная с 00:00:00, после этого 00:15:00, 00:30:00 и так далее. Но на диаграмме у меня неправильная маркировка в «минутах»: 06, 12, 24, ... enter image description here

Когда я уменьшаю масштаб или меняю время, которое имеет больше 1 дневной период. Нет проблем.

Один из способов - использовать distribution: 'series'. Для 1 дня визуализация это то, что я хочу: enter image description here

После этого, если я изменю период времени более чем на 1 день. На этикетках отображаются только часы и минуты без указания даты: enter image description here

Вот сценарий:

      var timeFormat = 'DD MMM YYYY г. kk:mm:ss ч.';
      var progress = document.getElementById('animationProgress');
      var dateANDtime = [];
      var Grazhod200 = [];
      var Grazhod350 = [];
      var Grazhod600 = [];

      var barGraph;

      for (var i in data) {
        dateANDtime.push(data[i].recordtime);
        Grazhod200.push(data[i].razhod200);
        Grazhod350.push(data[i].razhod350);
        Grazhod600.push(data[i].razhod600);
      }
      function getRandomColor() {
        var r = Math.floor(Math.random() * 250);
        var g = Math.floor(Math.random() * 255);
        return "rgb(" + 100 + "," + g + "," + 1 + ")";
         }
         function getRandomColorBorder() {
           var r = Math.floor(Math.random() * 250);
           var g = Math.floor(Math.random() * 250);
           return "rgb(" + 120 + "," + g   + "," + 100 + ")";
            }


      var chartdata = {
        labels: dateANDtime,
        datasets: [
        {
          fill: false,
          label: ' (КМ 0+600)',
          backgroundColor: getRandomColor(),
          borderColor: getRandomColorBorder(),
          data: Grazhod600,
          hidden: false
        },
        {
          fill: false,
          label: ' (КМ 9+200)',
          backgroundColor: getRandomColor(),
          borderColor: getRandomColorBorder(),
          data: Grazhod200,
          hidden: false
        },
        {
          fill: false,
          label: ' (КМ 11+350)',
          backgroundColor: getRandomColor(),
          borderColor: getRandomColorBorder(),
          data: Grazhod350,
          hidden: false
        }
      ]
    };
    $('#reset_zoom').click(function() {
      barGraph.resetZoom();
    })
    $("#save-btn").click(function() {
      $("#mycanvas").get(0).toBlob(function(blob) {
        saveAs(blob, "chart_1.png");
      });
    });


    var config = {

      type: 'line',
      data: chartdata,
      options: {
        tooltips: {
          callbacks: {
            label: function(tooltipItem, data) {
              var label  = data.datasets[tooltipItem.datasetIndex].label || '';

              if (label == 'Grazhod200') {
              return label  + ' : ' + tooltipItem.yLabel + ' m3/s';
              }
              if (label == 'Grazhod350') {
              return label  + ' : ' + tooltipItem.yLabel + ' m3/s';
              }
              if (label == 'Grazhod600') {
              return label  + ' : ' + tooltipItem.yLabel + ' m3/s';
              }
              return label  + ' : ' + tooltipItem.yLabel ;
            }
          }
        },
        responsive: true,
        title: {
          display: true,
          text: 'Диаграма:'
        },
        scales: {
          yAxes: [{
            type: type,
            scaleLabel: {
              display: true,
              labelString: 'Стойност'
            },
            ticks: {
              beginAtZero: false
            }
          }],
          xAxes: [{
            type: 'time',
            time: {
              tooltipFormat: timeFormat,
              displayFormats: {
                'week': 'll',
                'hour': timeFormat
              }
            },
            distribution: 'series',
            scaleLabel: {
              display: true,
              labelString: 'Дата/Час'
            },
            ticks: {
            }
          }]
        },
        // Container for pan options
        pan: {
          enabled: true,
          mode: 'x',
          speed: 10,
          threshold: 10
        },

        // Container for zoom options
        zoom: {
          enabled: true,

          // Zooming directions. Remove the appropriate direction to disable
          // Eg. 'y' would only allow zooming in the y direction
          mode: 'x'

        },
        animation: {
          duration: 2000,
          onProgress: function(animation) {
            progress.value = animation.currentStep / animation.numSteps;
          },
          onComplete: function() {
            window.setTimeout(function() {
              progress.value = 0;
            }, 2000);
          }
        },
        legend: {
          display: true,
          labels: {
            //fontColor: 'rgb(255, 99, 132)'
            usePointStyle: true
          }
        }
      },
      plugins: [{
        beforeDraw: function(c) {
          var reset_zoom = document.getElementById("reset_zoom"); //reset button
          var ticks = c.scales['x-axis-0', 'y-axis-0'].ticks.length; //x-axis ticks array
          var labels = c.data.labels.length; //labels array
          if (ticks < labels) reset_zoom.hidden = false;
          else reset_zoom.hidden = true;
        }
      }]
    };

    var type = 'linear';

    var ctx = document.getElementById("mycanvas");

    barGraph = new Chart(ctx, config);
    barGraph.update();
    window.onload = function() {
      var ctx = document.getElementById("mycanvas");
      window.myLine = barGraph;
    };

  }
...