简体   繁体   中英

Chart.js: Get Hidden Datasets

I have a multiseries line chart using Chart.js and I've been trying to figure out how to get hidden datasets from a Chart.js object. I want to display the filtered data in a table besides the Chart.

I tried adding a hidden variable for each dataset but I still am having trouble retrieving which datasets are hidden.

how do you hide your datasets?
I just checked Chart.js document, and found that they have hidden option.
So, why don't you see at the hidden option?

// test chart.
var data =  {
    labels: ["Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7"],
    datasets: [
        {
            label: "line-1",
            borderColor: 'rgb(255, 0, 0)',
            data: [20, 26, 12, 43, 33, 21, 29],
            // hidden
            hidden: true
        },
        {
            label: "line-2",
            borderColor: 'rgb(0, 255, 0)',
            data: [10, 3, 24, 43, 23, 11, 51],
        },
        {
            label: "line-3",
            borderColor: 'rgb(0, 0, 255)',
            data: [16, 31, 22, 53, 24, 27, 69],
        }
    ]
};

// For hidden Label. (I don't know why datasets hasn't this option.)
var options = {
    legend: {
        labels: {
            filter: function(item, chart) {
                return !item.hidden;
            }
        }
    }
};

// Create the chart.
var myLineChart = new Chart($("#chart"), {
    type: 'line',
    data: data,
    options: options
});

// Get the hidden datasets based on the hidden column.
var hiddenDatasets = $.grep(myLineChart.data.datasets, function(line) {
    return line.hidden;
});

// See console.
console.log(hiddenDatasets);

Here's jsfiddle.

UPDATED I found that there is a useful method available.

var hiddenDatasets = [];
for(var i=0; i<myLineChart.data.datasets.length; i++) {
    // It seems some value updated in metadata, but there is a method available.
    // var metaDatasets = myLineChart.getDatasetMeta(i);
    if (!myLineChart.isDatasetVisible(i)) {
        // or myLineChart.getDatasetMeta(i);
        hiddenDatasets.push(myLineChart.data.datasets[i]);
    }
 }
 // See console.
 console.log(hiddenDatasets);

jsfiddle.

Found this thread googling, so in case there still isn't a better way to do this than checking datasets one by one, here is a filter() version to copypaste:

myChart.data.datasets.filter((ds, i) => !myChart.isDatasetVisible(i) ? ds : undefined);

Or the reverse to get only the visible ones:

myChart.data.datasets.filter((ds, i) => myChart.isDatasetVisible(i) ? ds : undefined);

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