Cannot get PieChart to update data after button click

138 views
Skip to first unread message

essasen

unread,
Nov 29, 2018, 4:48:50 PM11/29/18
to Google Visualization API
Here is my HTML file with the JavaScript


My problem is I cannot get anything to appear. What am i doing wrong. 

<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      
       // Load the Visualization API and the piechart package.
      google.visualization.load('current', {'packages':['corechart']});

      // Set a callback to run when the Google Visualization API is loaded.
      google.visualization.setOnLoadCallback(drawChart);

        var data1 = google.visualization.arrayToDataTable([
          ['Language', 'Speakers (in millions)'],
          ['Cat 1', 26], ['Cat 3', 16], ['Cat 2', 30],
          ['Total', 100]
        ]);
        var data2 = google.visualization.arrayToDataTable([
          ['Language', 'Speakers (in millions)'],
          ['Cat 1', 100], ['Cat 3', 200], ['Cat 2', 300],
          ['Total', 400]
        ]);

        var options = {
          title: 'Indian Language Use',
          legend: 'none',
          pieSliceText: 'label',
          slices: {  1: {offset: 0.2},
                     2: {offset: 0.3},
                     3: {offset: 0.4},
                     4: {offset: 0.5},
          },
          animation: {
          startup:true,
          duration: 1000,
          easing: 'in'
          }
        };
  

        var current = 0;

        var data = [];
        data[0] = google.visualization.arrayToDataTable(data1);
        data[1] = google.visualization.arrayToDataTable(data2);

        var chart = new google.visualization.PieChart(document.getElementById('piechart'));
        var button = document.getElementById('b1');


     function drawChart() {
      // Disabling the button while the chart is drawing.
      button.disabled = true;
      google.visualization.events.addListener(chart, 'ready',
          function() {
            button.disabled = false;
            button.value = 'Switch to ' + (current ? 'Tea' : 'Coffee');
          });
      options['title'] = 'Monthly ' + (current ? 'Coffee' : 'Tea') + ' Production by Country';

      chart.draw(data[current], options);
    }



    button.onclick = function() {
      current = 1 - current;
      drawChart();
    }

    drawChart();


    </script>
  </head>
  <body>
    <div id="piechart"></div>
    <div id="b1"></div>
  </body>
</html>


If someone could explain why the charts or the button is not being drawn. I would be much appreciative.

Thank you.

Arthur Hebert

unread,
Apr 22, 2023, 5:30:54 PM4/22/23
to Google Visualization API
<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
     
       // Load the Visualization API and the piechart package.
      //google.visualization.load('current', {'packages':['corechart']});
      google.charts.load('current', {'packages':['corechart']});


      // Set a callback to run when the Google Visualization API is loaded.
      // google.visualization.setOnLoadCallback(drawChart);
      google.charts.setOnLoadCallback(init);
      function init() {

        var data1 = [

          ['Language', 'Speakers (in millions)'],
          ['Cat 1', 26], ['Cat 3', 16], ['Cat 2', 30],
          ['Total', 100]
        ];
        var data2 = [

          ['Language', 'Speakers (in millions)'],
          ['Cat 1', 100], ['Cat 3', 200], ['Cat 2', 300],
          ['Total', 400]
        ];
    <input type="button" id="b1" value="Change Value"></input>
  </body>
</html>

Arthur Hebert

unread,
Apr 24, 2023, 11:15:51 AM4/24/23
to Google Visualization API
I see that this is an old post. I'm trying to figure out the same problem. 

Chrome developer tools can be opened with Shift+Ctrl+J. I got 2 errors. 
I apparently fixed 1 with  <!DOCTYPE html>. 
The other one is a navigator error or something. Still lost. 

On Thursday, November 29, 2018 at 3:48:50 PM UTC-6 essasen wrote:

Ray Thomas

unread,
Apr 27, 2023, 10:34:37 PM4/27/23
to Google Visualization API
Hello Arthur,

I couldn't figure out why your code wasn't working so I started over. Two ways of doing this came to mind, one way is to draw the charts then use a button to toggle the display property of the divs on and off. The other way was to redraw the charts on a button click in a single div.

Method 1 - hide/display the chart divs

I used https://developers.google.com/chart/interactive/docs/basic_multiple_charts as a starting point and added a button to show or hide the chart divs.

The code for this is:

<script type="text/javaScript">
  // Create a namespace
  var pizzas = (function() {

      // Load Charts and the corechart package.
      google.charts.load('current', {'packages':['corechart']});

      // Draw the pie chart for Sara's pizza when Charts is loaded.
      google.charts.setOnLoadCallback(drawSaraChart);

      // Draw the pie chart for the Tony's pizza when Charts is loaded.
      google.charts.setOnLoadCallback(drawTonyChart);

      // Callback that draws the pie chart for Sara's pizza.
      function drawSaraChart() {

        // Create the data table for Sara's pizza.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Topping');
        data.addColumn('number', 'Slices');
        data.addRows([
          ['Mushrooms', 1],
          ['Onions', 1],
          ['Olives', 2],
          ['Zucchini', 2],
          ['Pepperoni', 1]
        ]);

        // Set options for Sara's pie chart.
        var options = {title:'How Much Pizza Sara Ate Last Night',
   width:400,
   height:300};

        // Instantiate and draw the chart for sara's pizza.
        var chart = new google.visualization.PieChart(document.getElementById('sara_chart_div'));
        chart.draw(data, options);
      }

      // Callback that draws the pie chart for tony's pizza.
      function drawTonyChart() {

        // Create the data table for Tony's pizza.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Topping');
        data.addColumn('number', 'Slices');
        data.addRows([
          ['Mushrooms', 2],
          ['Onions', 2],
          ['Olives', 2],
          ['Zucchini', 0],
          ['Pepperoni', 3]
        ]);

        // Set options for Tony's pie chart.
        var options = {title:'How Much Pizza Tony Ate Last Night',
   width:400,
                       height:300};

        // Instantiate and draw the chart for Tony's pizza.
        var chart = new google.visualization.PieChart(document.getElementById('tony_chart_div'));
        chart.draw(data, options);
      }
})();
    </script>

and the HTML is:

<button onclick="showhidePizza()">Toggle Charts</button>
<div id="sara_chart_div" style="display:none;"></div>
<!-- <div id="sara_chart_div"></div> -->
<div id="tony_chart_div"></div>

and the code for the button is:

<script language="javaScript">
function showhidePizza() {
  var saraDiv = document.getElementById("sara_chart_div");
  var tonyDiv = document.getElementById("tony_chart_div");
  if (saraDiv.style.display === "none") {
    saraDiv.style.display = "block";
tonyDiv.style.display = "none";
  } else {
    saraDiv.style.display = "none";
tonyDiv.style.display = "block";
  }
}
</script>

Method 2: - redraw the charts on a button click

This was adapted from https://stackoverflow.com/questions/38161862/change-google-chart-data-and-appearance-with-button - WhiteHat who worte the original is a genius with the Chart API.

The script is:

<script language="javaScript">
// Create a namespace
var speakers = (function() {
google.charts.load('current', {
  'callback': function () {

    var data1 = google.visualization.arrayToDataTable([
      ['Language', 'Speakers (in millions)'],
      ['Cat 1', 26], ['Cat 3', 16], ['Cat 2', 30]
    ]);

    var data2 = google.visualization.arrayToDataTable([
      ['Language', 'Speakers (in millions)'],
      ['Cat 1', 100], ['Cat 3', 200], ['Cat 2', 300]
    ]);

    var options = {
          title: 'Indian Language Use',
          legend: 'none',
          pieSliceText: 'label',
          slices: {  1: {offset: 0.2},
                     2: {offset: 0.3},
                     3: {offset: 0.4},
                     4: {offset: 0.5},
          },
          animation: {
          startup:true,
          duration: 1000,
          easing: 'in'
          }
        };

    var chart = new google.visualization.PieChart(document.getElementById('language_div'));
    chart.draw(data1, options);
 
document.getElementById('toggleData').addEventListener('click', function () {
var btnValue = document.getElementById('toggleData').value;
if (btnValue == "0"){
    chart.draw(data1, options);
    btnValue = "1";}
else {
chart.draw(data2, options);
btnValue = "0";}
document.getElementById('toggleData').value = btnValue;
},  false);

    document.getElementById('data1').addEventListener('click', function () {
      chart.draw(data1, options);
    }, false);

    document.getElementById('data2').addEventListener('click', function () {
      chart.draw(data2, options);
    }, false);

  },
  'packages':['corechart']
});
})();
</script>

The HTML is:

<button id="toggleData" value="1">Toggle Charts</button>
<input type="button" id="data1" value="Data1" />
<input type="button" id="data2" value="Data2" />
<div id="language_div"></div>

I added both methods to the bottom of https://brisray.com/google-charts/multiple.htm so you can see them in action.

Arthur Hebert

unread,
Apr 28, 2023, 11:41:24 PM4/28/23
to Google Visualization API
Hello Ray, 

I opened the earlier email confirmations that I received for this thread. It's my understanding (which might be wrong) that the day of approval is what is shown. 
My two earlier posts appear to happen in the wrong order, but that's because of when they were approved. 

Anyways, I was in ok shape on the code. Just now, I copied and pasted the code that I posted earlier, and it worked for me (that's the post labeled April 22). 

However, your comments helped me understand how this stuff works better. 
Possibly the most useful part was the 
resource that you posted at the end. 

The Google documentation is helpful, but a couple of holes (my newcomer's view) made things a lot more difficult to understand. 

Thanks for helping me out. 


Reply all
Reply to author
Forward
0 new messages