Chartjs linechart with only one point - how to center

后端 未结 4 1189
一整个雨季
一整个雨季 2020-12-19 01:45

I have a chartjs linechart diagram to show the sales of different products on a range of dates. The user can select a date range (for example from 2015-12-01 to 2015-12-10)

4条回答
  •  春和景丽
    2020-12-19 01:57

    Wanted to add to the above answer and say that I got a similar effect on a time series scatter plot using this:

    if (values.length === 1) {
            const arrCopy = Object.assign({}, values);
            values.unshift({x: arrCopy[0].x - 86400000, y: null});
            values.push({x: arrCopy[0].x + 2 * 86400000, y: null});
    }
    

    That only handles for a single point, however. To add in functionality for multiple points, I did the following:

    const whether = (array) => {
        const len = array.length;
        let isSame = false;
        for (let i = 1; i < len; i++) {
            if (array[0].x - array[i].x >= 43200000) {
                isSame = false;
                break;
            } else {
                isSame = true;
            }
        }
        return isSame;
    }
    if (values.length === 1 || whether(arr[0])) {
            const arrCopy = Object.assign({}, values);
            values.unshift({x: arrCopy[0].x - 86400000, y: null});
            values.push({x: arrCopy[0].x + 2 * 86400000, y: null});
    }
    

    You might notice I'm just subtracting/adding a day in milliseconds into the x values. To be honest, I was just having the worst of times with moment.js and gave up haha. Hope this helps someone else!

    Note: my code has a tolerance of 43200000, or 12 hours, on the time. You could use moment.js to compare days if you have better luck with it than I did tonight :)

提交回复
热议问题