如何在Charts.js中按日期过滤数据

vom3gejh  于 2023-04-20  发布在  Chart.js
关注(0)|答案(1)|浏览(216)

我正在使用charts.js,我有折线图。我试图通过标签(日期)过滤数据。我已经创建了两个输入开始和结束日期输入。当用户更改开始/结束日期图表应按日期过滤

var ctx = document.getElementById('myChart').getContext('2d');
var lbls = ["07/11/2020","07/12/2020","07/13/2020",];
var dt = ["27","24","30",]

var chart = new Chart(ctx, {
  // The type of chart we want to create
  type: 'line', // also try bar or other graph types

  // The data for our dataset
  data: {
    labels: lbls,
    // Information about the dataset
    datasets: [{
      label: "Gold Price",
      backgroundColor: 'lightblue',
      borderColor: 'royalblue',
      data: dt,
    }]
  },

  // Configuration options
  options: {
    layout: {
      padding: 10,
    },
    legend: {
      position: 'bottom',
    },
    title: {
      display: true,
      text: "Gold Price"
    },
    scales: {
      yAxes: [{
        scaleLabel: {
          display: true,
          labelString: 'Price in USD'
        }
      }],
      xAxes: [{
        scaleLabel: {
          display: true,
          labelString: 'Date'
        }
      }]
    }
  }
});
<div class="chart" style="width:100%">
   <input type="date" onfocus="(this.type='date')" placeholder="Start Date" id="start"><input type="date" onfocus="(this.type='date')" placeholder="End Date" id="end">
            <canvas id="myChart" width="400" height="200"></canvas>
</div>
      
      
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js"></script>

这是我的代码,我不知道我该怎么做。

snvhrwxg

snvhrwxg1#

试试这个:

<input type="date" id="startdate" value="2020-11-07" @onchange="filterDataOnDate"/>
<input type="date" id="enddate" value="2020-11-13" @onchange="filterDataOnDate" />

//Filter date
function filterDataOnDate(){
    const date = [...labels]
    const startdate = document.getElementById('startdate')
    const enddate = document.getElementById('enddate')

    //get the index number  in array
    const indexstartdate = date.indexOf(startdate.value);
    const indexenddate = date.indexOf(enddate.value);

    //slice the array
    const filterdate = date.slice(indexstartdate, indexenddate + 1);
    chart.config.data.labels = filterdate;

    //update the chart
    chart.update();
}

相关问题