gpt4 book ai didi

javascript - Chart.js - 加载后使用标签字符串隐藏行

转载 作者:行者123 更新时间:2023-12-03 04:50:40 30 4
gpt4 key购买 nike

使用chart.js ,我有一个折线图,显示在 .net Web 应用程序中编译的数据集。

加载数据后是否可以根据标签名称将行设置为隐藏/禁用?

有一个hidden flag在 Chart.js 中,可以在加载时隐藏数据集,但这是在最初定义数据集时设置的。由于数据已在 View 中定义,因此我无法使用此标志。例如

var viewsByMonthChartCtx = new Chart(viewsByMonthChartCtx, {
type: 'line',
data: {
labels: ['February 2017','March 2017'],
datasets:
[ { label: 'Home', data: [100,120 ] }, // I want to set 'hidden: true' to the Home dataset post initialization
{ label: 'Search', data: [200,240 ] } ]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
}
});

最佳答案

如果您想在图表初始化(并呈现)后隐藏数据集,那么您仍然可以使用数据集 hidden: true 属性。您只需从图表实例访问数据集并将属性设置为 true。

下面是一个示例,其中与标签匹配的数据集在页面加载 5 秒后隐藏。

// the dataset label we want to hide after chart is initialized
var hiddenLabel = 'My Second Dataset';
var timerDuration = 5;

// hide a dataset after X seconds
setTimeout(function() {
var indexToHide = -1;

// find which dataset matches the label we want to hide
myLine.config.data.datasets.forEach(function(e, i) {
if (e.label === hiddenLabel) {
indexToHide = i;
}
});

// get the dataset meta object so we can hide it
var meta = myLine.getDatasetMeta(indexToHide);

// hide the dataset and re-render the chart
meta.hidden = true;
myLine.update();
}, timerDuration * 1000);

如您所见,您只需迭代数据集即可找到具有匹配标签的数据集的索引,然后只需将隐藏属性设置为 true 并更新图表即可。

这是一个codepen这演示了一个完整的工作示例。

话虽如此,目前尚不清楚为什么在隐藏图表后要执行此操作。如果您已经知道要在页面加载时隐藏哪个数据集,那么您可以动态组合数据和选项图表配置,并以编程方式将隐藏标志设置为 true。这是一个例子。

// the dataset label we want to hide
var hiddenLabel = 'My Second Dataset';

// build our data and options config (if needed you could build the datasets dynamically from dynamic data (this example is static)
var config = {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First Dataset",
backgroundColor: chartColors.red,
borderColor: chartColors.red,
data: [5, 10, 25, 15, 10, 20, 30],
fill: false,
}, {
label: "My Second Dataset",
fill: false,
backgroundColor: chartColors.blue,
borderColor: chartColors.blue,
data: [5, 0, 12, 5, 25, 35, 15],
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js Hide Dataset Matching "My Seconds Dataset" After 3 Seconds'
},
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Month'
}
}],
}
}
};

// iterate over our datasets to find the one we want to hide
config.data.datasets.forEach(function(e) {
if (e.label === hiddenLabel) {
e.hidden = true;
}
});

// instantiate the chart
var myLine = new Chart($('#canvas'), config);

关于javascript - Chart.js - 加载后使用标签字符串隐藏行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42674456/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com