简体   繁体   English

如何在 Chart.js 3.+ 上使用缩放和平移在我的图表数据集上显示特定数据范围?

[英]How to display specific data range on my chart's dataset using Zoom and Pan on Chart.js 3.+?

I have a line chart for messages sent x day/month and I also have two datepickers on top of it.我有一个关于 x 天/月发送的消息的折线图,我还有两个日期选择器。 I want to be able to select a start date, an ending date and the chart reads those dates and display this exactly range of points.我希望能够 select 一个开始日期,一个结束日期,图表读取这些日期并显示这个精确的点范围。 I already have zoom and pan configured on my chart.js file and I can do it manually, but I was wondering how can I do that through what I just described.我已经在我的 chart.js 文件上配置了缩放和平移,我可以手动进行,但我想知道如何通过我刚才描述的内容来做到这一点。

我的图表

On this picture I have 3 months of data already.在这张照片上,我已经有 3 个月的数据了。 It always begins displaying 1 month.它总是开始显示 1 个月。

I did it: I created a function to be called after every date change on my datepicker that is like that:我做到了:我创建了一个 function 在我的 datepicker 上的每个日期更改后调用,就像这样:

function filterDate(initialDate, finalDate){
    //first I cloned my dataset [labels (x) and data (y)] like this:
    labelsData2 = [...labelsData];
    sentData2 = [...sentData];

    //then I used the datepicker's values to pinpoint the index of both dates (initial and final) on my labelsData2 array, sliced the array so it now contains only the range of dates that I want and stored the value on labelsData2 again
    labelsData2 = labelsData2.slice(labelsData2.indexOf(initialDate), mesesData2.indexOf(finalDate) + 1); //<- +1 to prevent the index 0 to mess my result.

    //I used the same indexOf to slice my sentData2 array as well, since they have the same length.
    sentData2 = sentData2.slice(labelsData2.indexOf(initialDate), mesesData2.indexOf(finalDate) + 1);

    //then I updated my chart!
    myChart.data.datasets[0].data = sentData2;
    myChart.data.labels = labelsData2;
    myChart.update();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM