简体   繁体   中英

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. 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. 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.

我的图表

On this picture I have 3 months of data already. It always begins displaying 1 month.

I did it: I created a function to be called after every date change on my datepicker that is like that:

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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