简体   繁体   中英

Create data array for google charts

I am using google charts and I would like to create a simple bar chart with a data array. If I write out the data array manually like this, the chart is working fine:

 var data = [['Municipality', 'CWR', {role: 'style'}],
                  ['Kleinharras', 4.15,'color: #e5e4e2'],
                  ['Stillfried', 4.87,'color: #e5e4e2'],
                  ['Grub an der March', 4.95,'color: #e5e4e2'],
                  ['Großschweinbarth', 3.92,'color: #e5e4e2'],];  

  google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
  var data = google.visualization.arrayToDataTable(data);

  var options = {
      title: 'Crop Water Requirement [mm]',
      vAxis: {title: 'Municipality',  titleTextStyle: {color: 'black'}}
    };

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

    chart.draw(data, options);
  }

However, if I want to create the data array automatically with a loop, its not working and the chart doesnt show:

 var data = [['Municipality', 'CWR', {role: 'style'}]];
         for (i = 0; i < valuesx.length; i++) {
                data[i + 1] = [valuesx[i], valuesy[i], 'color: #e5e4e2'];  
         }

If i print out both arrays, they look identical , however for some reason google charts doesnt accept the second data array. Any suggestions?

I made it work but I dont really know why it didnt work in the first place. After the construction of my array with the loop (see code above) I do the following:

var data = google.visualization.arrayToDataTable(data);

As you can see, I am creating a new variable named data from my array that is also called data. And this is were the error occurs.

If I simply rename my data array, ie to data2, like this:

var data2 = [['Municipality', 'CWR', {role: 'style'}]];
             for (i = 0; i < valuesx.length; i++) {
                    data2[i + 1] = [valuesx[i], valuesy[i], 'color: #e5e4e2'];  
             }

and run this command:

  var data = google.visualization.arrayToDataTable(data2);

the chart finally shows.

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