简体   繁体   中英

Javascript Google Charts change data

I'm trying to create a function to change the data in a Google Charts scatter chart but when I call the function the chart doesn't change. Heres the code:

<script type="text/javascript">

var years = [2001, 2002, 2003, 2004, 2005];
var sales = [1, 2, 3, 4, 5];

google.load("visualization", "1", {packages:["corechart"]});

 google.setOnLoadCallback(drawChart);

  var data;
  var options;
  var chart;

  function drawChart() {
        data = new google.visualization.DataTable();
  data.addColumn('number', 'years');
  data.addColumn('number', 'sales');

  for(i = 0; i < years.length; i++)
    data.addRow([years[i], sales[i]]);

        options = {
          title: 'Age vs. Weight comparison',
          hAxis: {title: 'Age', minValue: 0, maxValue: 1},
          vAxis: {title: 'Weight', minValue: 0, maxValue: 1},
          legend: 'none'
        };

        chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));

        chart.draw(data, options);
      }

    $(document).ready(function(){
         changeData();
    });

     function changeData()
     {
        data.addRow(10, 10);
        chart.draw(data, options); 
     }   
</script>

There are some errors in the code.

The first one: you are calling on load google.setOnLoadCallback(drawChart); and also changeData(); It seems that changeData() is started first because there is error reported:

Uncaught TypeError: Cannot call method 'addRow' of undefined

One option to fix it is to call changeData(); at the end of drawChart() function.

The next one: call

data.addRow(10, 10);

has to be changed to something like:

data.addRow([2006, 10]);

because addRow() expects an array.

And min and max values have to be changed.

See example at jsbin .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM