简体   繁体   中英

chart.js - tooltip callback function ignore hidden datasets when deselecting legend

I'm using a chart.js linechart with stacked datasets.

When hovering over a single datapoint, it only shows the value of the current dataset.

I added the total (of this and the 'below' datasets) next to the value.

This works fine until I deselect a dataset from the legend, because the total will not be updated and ignore the hidden dataset.

This is the code to show the value of the dataset and the total.

callbacks: {
    label: function(tooltipItem, data) {
        let total = 0;
        let value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
        let stop = tooltipItem.datasetIndex+1;
        for (let i = 0; i < stop; i++) {
            total += data.datasets[i].data[tooltipItem.index];
        }
        total = Math.floor(total * 100) / 100;
        return 'Value: ' + value + ' Total: ' + total;
    }
}

You can check this out here https://jsfiddle.net/x1zycrh4/1/

When you hover over any point you see the value and the total next to it.

But when you deselect the "Available" dataset for example, the tooltip total is not updated.

For this I'd like to ignore hidden datasets from my tooltip callback function, but I can't seem to access 'data.datasets[tooltipItem.datasetIndex].hidden'.

I revisited this problem today and found a solution really quick.

Accessing the 'hidden' property can be done like in this post: Tell if an line is hidden

This is the updated code:

callbacks: {
    label: function(tooltipItem, data) {
        let total = 0;
        let value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
        let stop = tooltipItem.datasetIndex+1;
        for (let j = 0; j < stop; j++) {
            if(!data.datasets[j]._meta[Object.keys(data.datasets[j]._meta)[0]].hidden) {
                total += data.datasets[j].data[tooltipItem.index];
            }
        }
    total = Math.floor(total * 100) / 100;
    return 'Value: ' + value + ' Total: ' + total;
    }
}

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