5👍
After thoroughly researching this, there doesn’t appear to be any built in function to toggle entire datasets. I used the .destroy()
function to remove the entire existing chart, and then some logic to redraw it with the necessary datasets.
EDIT: Here’s a fiddle with my full code if it’s helpful to anyone -> http://jsfiddle.net/21xg27kr/4/
2👍
Here is a line chart with two datasets. By updating the datasets and calling the .update()
method. The benefit here is you don’t need to destroy the whole chart, and there is a nice animated transition which can be disabled.
TL:DR; solution on jsfiddle
Step by Step:
-
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>