Show/hide lines/data in Google Chart
To get your required output check this code.
google.visualization.events.addListener(chart, 'select', function () {
var sel = chart.getSelection();
// if selection length is 0, we deselected an element
if (sel.length > 0) {
// if row is null, we clicked on the legend
if (sel[0].row == null) {
var col = sel[0].column;
if (columns[col] == col) {
// hide the data series
columns[col] = {
label: data.getColumnLabel(col),
type: data.getColumnType(col),
calc: function () {
return null;
}
};
// grey out the legend entry
series[col - 1].color = '#CCCCCC';
}
else {
// show the data series
columns[col] = col;
series[col - 1].color = null;
}
var view = new google.visualization.DataView(data);
view.setColumns(columns);
chart.draw(view, options);
}
}
});
Instead of having check box use the legend to hide/show the lines.
Check this for the working sample: jqfaq.com
try this
Mark up:
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
<button type="button" id="hideSales" >Hide Sales</button>
<button type="button" id="hideExpenses" >Hide Expence</button>
</body>
Script:
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
var hideSal = document.getElementById("hideSales");
hideSal.onclick = function()
{
view = new google.visualization.DataView(data);
view.hideColumns([1]);
chart.draw(view, options);
}
var hideExp = document.getElementById("hideExpenses");
hideExp.onclick = function()
{
view = new google.visualization.DataView(data);
view.hideColumns([2]);
chart.draw(view, options);
}
}
</script>
Recently the behavior of the select
event changed so Abinaya Selvaraju's answer needs a slight fix
if (typeof sel[0].row === 'undefined') {
...
}
becomes
if (sel[0].row == null) {
...
}