Chartjs-Chart js: generate dynamic labels according to the data

0๐Ÿ‘

I think it would be the best to add two tabs with names monthly and yearly, so user can easy click on tab to change views. For example on monthly view, it will be too much to show all months in one chart(I think it will be mess with data), you should do this only with one month. Just add datetimepicker only with months(same for years), on change you can call function which will change chart also(see here how it works https://www.tutorialspoint.com/How-does-jQuery-Datepicker-onchange-event-work). Also you can set the range of years.

So, now when you have function which will change chart, just change data by getting selected month and your data for this month. There is an update function, which you can call when you have updated data and it will change chart(See docs: https://www.chartjs.org/docs/latest/developers/updates.html).

Here is an example of code for adding new dataset to existing chart by clicking button:

document.getElementById('addDataset').addEventListener('click', function() {
        var colorName = colorNames[barChartData.datasets.length % colorNames.length];
        var dsColor = window.chartColors[colorName];
        var newDataset = {
            label: 'Dataset ' + (barChartData.datasets.length + 1),
            backgroundColor: color(dsColor).alpha(0.5).rgbString(),
            borderColor: dsColor,
            borderWidth: 1,
            data: []
        };

        for (var index = 0; index < barChartData.labels.length; ++index) {
            newDataset.data.push(randomScalingFactor());
        }

        barChartData.datasets.push(newDataset);
        window.myBar.update();
    });

0๐Ÿ‘

Just in case anybody was searching and found this thread because they wanted dynamic units for their plotted points in Chart.js, then the below code will give you and idea of how to configure your options -> tooltips -> callbacks -> label

options: {
    tooltips: {
        callbacks: {
            label: (item) => {
                if (condition1 == true) {
                    return (item.yLabel / 1000000000).toFixed(2) + ' Gbps'
                }
                else if (condition2 == true) {
                    return (item.yLabel / 1000000).toFixed(2) + ' Mbps'
                }
                else if (condition3 == true) {
                    return (item.yLabel / 1000).toFixed(2) + ' Kbps'
                }
                else {
                    return item.yLabel.toFixed(2) + ' bps'
                }
            },
        },
    },
},

This is an example that converts bps to Kbps, Mbps, Gbps, etc. as necessary.

Leave a comment