Show/hide columns by clicking on legend labels
by Alex Azuero
HTML
<script src="http://www.google.com/jsapi?fake=.js"></script>
<div id="chart_div"></div>
<div id="creativeCommons" style="text-align: center; width: 400px;">
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_US"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by-nc-sa/3.0/88x31.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" href="http://purl.org/dc/dcmitype/InteractiveResource" property="dct:title" rel="dct:type">Code to turn on or off data series by clicking on legend entries</span> by <span xmlns:cc="http://creativecommons.org/ns#" property="cc:attributionName">Andrew Gallant</span> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_US">Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License</a>.
</div>
JavaScript
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'Y 1');
data.addColumn({type: 'boolean', role: 'certainty'});
data.addColumn('number', 'Y 2');
data.addColumn({type: 'string', role: 'annotation'});
data.addColumn({type: 'boolean', role: 'certainty'});
data.addColumn('number', 'Y 3');
data.addColumn({type: 'boolean', role: 'certainty'});
// add random data
var y1 = 50, y2 = 50, y3 = 50;
for (var i = 0; i < 30; i++) {
y1 += ~~(Math.random() * 5) * Math.pow(-1, ~~(Math.random() * 2));
y2 += ~~(Math.random() * 5) * Math.pow(-1, ~~(Math.random() * 2));
y3 += ~~(Math.random() * 5) * Math.pow(-1, ~~(Math.random() * 2));
data.addRow([i, y1, (~~(Math.random() * 2) == 1), y2, y2.toString(), (~~(Math.random() * 2) == 1), y3, (~~(Math.random() * 2) == 1)]);
}
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'chart_div',
dataTable: data,
options: {
width: 600,
height: 400
}
});
// create columns array
var columns = [0];
/* the series map is an array of data series
* "column" is the index of the data column to use for the series
* "roleColumns" is an array of column indices corresponding to columns with roles that are associated with this data series
* "display" is a boolean, set to true to make the series visible on the initial draw
*/
var seriesMap = [{
column: 1,
roleColumns: [2],
display: true
}, {
column: 3,
roleColumns: [4, 5],
display: true
}, {
column: 6,
roleColumns: [7],
display: false
}];
var columnsMap = {};
var series = [];
for (var i = 0; i < seriesMap.length; i++) {
var col =...