我有一个使用Chart.js的多系列折线图,并且我一直试图找出如何从Chart.js对象获取隐藏数据集的方法。我想在图表旁边的表格中显示过滤的数据。
我尝试为每个数据集添加一个隐藏的变量,但是在检索哪些数据集被隐藏时仍然遇到困难。
答案 0 :(得分:3)
如何隐藏数据集?
我刚刚检查了Chart.js文档,发现它们具有隐藏选项。
那么,为什么看不到隐藏选项?
// 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);
已更新
我发现有一种有用的方法。
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);