我正在使用Chart.js创建一条线图。我希望有四个不同的数据集,所有数据集都默认可见,但可以通过点击按钮切换开关。如何实现这一点?我在文档中找不到答案。.addData(),.removeData()和.update()似乎都用于添加或删除现有数据集的值,而不是添加或删除整个数据集。我认为这应该是一个常用的特性,但我找不到任何答案。
.destroy()
函数来删除整个现有图表,然后使用一些逻辑重新绘制它所需的数据集。.update()
方法,您可以获得好处,即无需销毁整个图表,并且有一个漂亮的动画过渡(可以禁用)。Bring in Chart.js from a CDN
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
Create the HTML Canvas element that will hold the chart
<canvas id="line-chart"></canvas>
Hide/Show buttons for this example
Creating the chart, and the functions to update it live - notice that the same integer data needs to be copied in two places - in the initial creation, and in the show function.
<script>
lineChart = new Chart(document.getElementById("line-chart"), {
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [
{
label: "Set 1",
fill: true,
backgroundColor: "rgba(90,181,242,0.2)",
borderColor: "rgba(179,181,198,1)",
pointBorderColor: "#fff",
pointBackgroundColor: "rgba(179,181,198,1)",
data: [3, 1, 1, 0]
}, {
label: "Set 2",
fill: true,
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
pointBorderColor: "#fff",
pointBackgroundColor: "rgba(255,99,132,1)",
pointBorderColor: "#fff",
data: [1, 3, 3, 5]
}
]
},
options: {
title: {
display: true,
text: 'Chart Title'
}
}
});
function restoreLayer2(){
lineChart.data.datasets[1].data = [1, 3, 3, 5];
lineChart.update();
}
function removeLayer2() {
lineChart.data.datasets[1].data = [];
lineChart.update();
}
</script>
<chartObject>.update()
即可。 - orangecaterpillarupdate()
。 - orangecaterpillar