如何根据所选日期获取图表上的数据(使用日期选择器过滤数据图表JS)

How to get data on chart based on selected date (Filtering data Chart JS with datepicker)

我尝试使用如下代码获取特定日期的所有数据:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">

<title>Try Chart</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>


<link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">


<script>
$(document).ready(function(){
$.datepicker.setDefaults({
    dateFormat: 'yy-mm-dd'
  });
  $("#firstdatepicker").datepicker();
  $("#lastdatepicker").datepicker();
  $("#filter").click(function() {
    var from_date = $("#firstdatepicker").val();
    var to_date = $("#lastdatepicker").val();
    if (from_date != '' && to_date != '') {
      console.log(from_date, to_date);
      var endpoint = '/api/data';

  $.ajax({
    method: "GET",
    url: endpoint,
    data: {
      from_date: from_date,
      to_date: to_date
    },
    success: function(data){
      console.log(data); //get all data
      //get data by fields
      var hum = [], time = [];
      for (var i=0; i<data.length; i++){
        hum.push(data[i].moisture);
        time.push(data[i].timestamp);
     }
      console.log(hum);
      console.log(time);
    //plot the chart

      var ctx = document.getElementById("moistureChart").getContext('2d');
      var moistureChart = new Chart(ctx, {
          type: 'line',
          data: {
              labels: time,
              datasets: [{
                  label: 'kelembaban',
                  data: hum,
                  backgroundColor: [
                      'rgb(68, 145, 252)'
                  ],
                  borderColor: [
                  '#331698'
                  ],
                  borderCapStyle: 'round',
                  borderWidth: 1
              }]
          },
          options: {
              reponsive: true,
              scales: {
                  yAxes: [{
                      ticks: {
                          beginAtZero:true,
                          stepSize:10
                      },
                        scaleLabel: {
                        display:     true,
                        labelString: 'kelembaban'
                    }
                  }],
                  xAxes: [{
                          display: true,
                          ticks: {
                            min: from_date,
                            max: to_date,
                          },
                        scaleLabel: {
                        display:     true,
                        labelString: 'Tanggal'
                    }
                  }]
              }
          }
      });
    },
    error: function(error_data){
      console.log(error_data)
    }
  });
} else {
  alert("Please Select Date");
}
  });    
});
</script>


</head>


<body>
<div class="container-fluid">
  <!--Breadcrumbs-->
  <ol class="breadcrumb">
    <li class="breadcrumb-item">
    </li>
    <li class="breadcrumb-item active">Charts</li>
    <li style="margin-left: 10px">
    data from <input type="text" id="firstdatepicker" name="firstdatepicker" value="2020-03-14">
    to <input type="text" id="lastdatepicker" name="lastdatepicker" value="2020-03-15">
    <input type="button" name="filter" id="filter" value="Filter" class="btn btn-info">
  </li>
  </ol>
    <div class="row"> 
      <div class="col-sm-1"></div>
        <canvas id="moistureChart" width="722" height="400">
        </canvas>
        <div class="col-sm-1"></div>
    </div>
</div>



<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery.ui.datepicker.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<!--buat kalender-->
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/themes/sunny/jquery-ui.min.css"></link>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css"></link>

</body>
</html>

数据来自 API 我使用 django rest 框架和 运行 在本地(本地主机)制作的数据。数据是这样的:

[
{
    "id": 2,
    "timestamp": "2020-03-15T11:46:10+07:00",
    "vibration": 3,
    "moisture": 70,
    "gps_latitude": "-7.7713794",
    "gps_longitude": "110.3753111",
    "gyro_x": 6.58,
    "gyro_y": 85.0,
    "gyro_z": -3.9,
    "accelero_x": 6.58,
    "accelero_y": 85.0,
    "accelero_z": -3.9,
    "displacement": 10,
    "node_id": 1
},
{
    "id": 6,
    "timestamp": "2020-03-15T12:00:10+07:00",
    "vibration": 3,
    "moisture": 75,
    "gps_latitude": "-7.7713794",
    "gps_longitude": "110.3753111",
    "gyro_x": 6.58,
    "gyro_y": 85.0,
    "gyro_z": -3.9,
    "accelero_x": 6.58,
    "accelero_y": 85.0,
    "accelero_z": -3.9,
    "displacement": 10,
    "node_id": 1
},
{
    "id": 7,
    "timestamp": "2020-03-15T13:00:10+07:00",
    "vibration": 3,
    "moisture": 75,
    "gps_latitude": "-7.7713794",
    "gps_longitude": "110.3753111",
    "gyro_x": 6.58,
    "gyro_y": 85.0,
    "gyro_z": -3.9,
    "accelero_x": 6.58,
    "accelero_y": 85.0,
    "accelero_z": -3.9,
    "displacement": 10,
    "node_id": 1
},
{
    "id": 8,
    "timestamp": "2020-03-16T07:00:00+07:00",
    "vibration": 3,
    "moisture": 80,
    "gps_latitude": "-7.7713794",
    "gps_longitude": "110.3753111",
    "gyro_x": 6.58,
    "gyro_y": 85.0,
    "gyro_z": -3.9,
    "accelero_x": 6.58,
    "accelero_y": 85.0,
    "accelero_z": -3.9,
    "displacement": 10,
    "node_id": 1
},
{
    "id": 9,
    "timestamp": "2020-03-17T07:00:00+07:00",
    "vibration": 3,
    "moisture": 70,
    "gps_latitude": "-7.7713794",
    "gps_longitude": "110.3753111",
    "gyro_x": 6.58,
    "gyro_y": 85.0,
    "gyro_z": -3.9,
    "accelero_x": 6.58,
    "accelero_y": 85.0,
    "accelero_z": -3.9,
    "displacement": 10,
    "node_id": 1
},
{
    "id": 10,
    "timestamp": "2020-03-18T07:00:00+07:00",
    "vibration": 3,
    "moisture": 77,
    "gps_latitude": "-7.7713794",
    "gps_longitude": "110.3753111",
    "gyro_x": 6.58,
    "gyro_y": 85.0,
    "gyro_z": -3.9,
    "accelero_x": 6.58,
    "accelero_y": 85.0,
    "accelero_z": -3.9,
    "displacement": 10,
    "node_id": 1
}
]

当我 select 从 3 月 15 日到 3 月 16 日的日期时,图表不显示 3 月 15 日到 16 日的数据,而是显示我在 API 中的所有数据。我的代码有什么错误吗?我认为我的代码中缺少某些东西。你能帮我看看代码吗?我希望图表只显示我在日期选择器上选择的日期的数据。不好意思,我是新手程序员

处理基于时间的数据时,您应该使用时间 ChartsJS,这样您就可以在 XAxe 中设置限制。

xAxes: [
        {
          type: "time",
          time: {
            minUnit: "minute",
            unit: "minute",
            unitStepSize: 4,
            min: moment(from_date).toDate(),//Date object type
            max: moment(to_date).toDate()//Date object type
          },
          ...
        }
      ],

请注意,使用此模式您需要使用以下数据:

{
    x: date,//Date object type
    y: value // Number
}

请注意,您对时间对象的限制应该是日期对象。我推荐使用库 momenjs 来操作日期数据,因为它有很多兼容性。例如,从服务器获取的数据的时间戳与 Safari 中的构造函数 Date 不兼容。但你可以做类似

的事情
moment(data.timestamp).toDate()