Show/hide lines/data in Google Chart - Javascript Google Chart

Javascript examples for Google Chart:Line Chart

Description

Show/hide lines/data in Google Chart

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript">
    window.onload=function(){//w ww .j a  va2  s  .c  o  m
  google.charts.load("current", {
    packages: ["corechart"]
  });
  google.charts.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);
    }
    var toggleSales = document.getElementById("toggleSales");
    var salesHidden = false;
    toggleSales.onclick = function() {
      salesHidden = !salesHidden;
      view = new google.visualization.DataView(data);
      if(salesHidden){
           view.hideColumns([1]);
      }
      chart.draw(view, options);
    }
    var toggleExp = document.getElementById("toggleExpenses");
    var expHidden = false;
    toggleExp.onclick = function() {
      expHidden = !expHidden;
      view = new google.visualization.DataView(data);
      if(expHidden){
           view.hideColumns([2]);
      }
      chart.draw(view, options);
    }
  }
    }

      </script> 
   </head> 
   <body> 
      <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> 
      <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> 
      <button type="button" id="toggleSales">Toggle Sales</button> 
      <button type="button" id="toggleExpenses">Toggle Expence</button>  
   </body>
</html>

Related Tutorials