Show Series that is Clicked & Hide All Others - CanvasJS
Show Series that is Clicked & Hide All Others - CanvasJS
by canvasjs
HTML
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<br/><!-- Just so that JSFiddle's Result label doesn't overlap the Chart -->
<div id="chartContainer" style="height: 360px; width: 100%;"></div>
JavaScript
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Show Series on Legend Click & Hide All Others"
},
legend: {
cursor: "pointer",
itemclick: itemclick
},
data: [
{
showInLegend: true,
type: "line",
dataPoints: [
{ x: 10, y: 5 },
{ x: 20, y: 9 },
{ x: 30, y: 17 },
{ x: 40, y: 32 },
{ x: 50, y: 22 },
{ x: 60, y: 14 },
{ x: 70, y: 25 },
{ x: 80, y: 18 },
{ x: 90, y: 20 }
]
},
{
showInLegend: true,
type: "line",
dataPoints: [
{ x: 10, y: 31 },
{ x: 20, y: 35 },
{ x: 30, y: 30 },
{ x: 40, y: 35 },
{ x: 50, y: 35 },
{ x: 60, y: 38 },
{ x: 70, y: 38 },
{ x: 80, y: 34 },
{ x: 90, y: 44 }
]
},
{
showInLegend: true,
type: "line",
dataPoints: [
{ x: 10, y: 25 },
{ x: 20, y: 30 },
{ x: 30, y: 20 },
{ x: 40, y: 45 },
{ x: 50, y: 30 },
{ x: 60, y: 10 },
{ x: 70, y: 15 },
{ x: 80, y: 18 },
{ x: 90, y: 20 }
]
}
]
});
addCountToSeries(chart);
chart.render();
function addCountToSeries(chart){
for(var i = 0; i < chart.options.data.length; i++) {
chart.options.data[i].clickCount = 0;
}
}
function itemclick(e) {
++e.dataSeries.clickCount;
for(var i = 0; i < e.chart.options.data.length; i++) {
if (e.dataSeries.clickCount % 2 === 0){
e.chart.options.data[i].visible = true;
}
else {
if (e.dataSeries !== e.chart.options.data[i]) {
e.chart.options.data[i].visible = false;
e.chart.options.data[i].clickCount = 0;
}
else{
e.dataSeries.visible = true;
}
}
}
e.chart.render();
}