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

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

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

  1. var ctx = document.getElementById('myChart').getContext('2d');
  2. var lbls = ["07/11/2020","07/12/2020","07/13/2020",];
  3. var dt = ["27","24","30",]
  4. var chart = new Chart(ctx, {
  5. // The type of chart we want to create
  6. type: 'line', // also try bar or other graph types
  7. // The data for our dataset
  8. data: {
  9. labels: lbls,
  10. // Information about the dataset
  11. datasets: [{
  12. label: "Gold Price",
  13. backgroundColor: 'lightblue',
  14. borderColor: 'royalblue',
  15. data: dt,
  16. }]
  17. },
  18. // Configuration options
  19. options: {
  20. layout: {
  21. padding: 10,
  22. },
  23. legend: {
  24. position: 'bottom',
  25. },
  26. title: {
  27. display: true,
  28. text: "Gold Price"
  29. },
  30. scales: {
  31. yAxes: [{
  32. scaleLabel: {
  33. display: true,
  34. labelString: 'Price in USD'
  35. }
  36. }],
  37. xAxes: [{
  38. scaleLabel: {
  39. display: true,
  40. labelString: 'Date'
  41. }
  42. }]
  43. }
  44. }
  45. });
  1. <div class="chart" style="width:100%">
  2. <input type="date" onfocus="(this.type='date')" placeholder="Start Date" id="start"><input type="date" onfocus="(this.type='date')" placeholder="End Date" id="end">
  3. <canvas id="myChart" width="400" height="200"></canvas>
  4. </div>
  5. <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js"></script>

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

snvhrwxg

snvhrwxg1#

试试这个:

  1. <input type="date" id="startdate" value="2020-11-07" @onchange="filterDataOnDate"/>
  2. <input type="date" id="enddate" value="2020-11-13" @onchange="filterDataOnDate" />
  3. //Filter date
  4. function filterDataOnDate(){
  5. const date = [...labels]
  6. const startdate = document.getElementById('startdate')
  7. const enddate = document.getElementById('enddate')
  8. //get the index number in array
  9. const indexstartdate = date.indexOf(startdate.value);
  10. const indexenddate = date.indexOf(enddate.value);
  11. //slice the array
  12. const filterdate = date.slice(indexstartdate, indexenddate + 1);
  13. chart.config.data.labels = filterdate;
  14. //update the chart
  15. chart.update();
  16. }
展开查看全部

相关问题