2

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?

2
  • Make sure valuesy[i] is number not string. Commented Nov 24, 2014 at 7:37
  • its a number array, I checked. Commented Nov 24, 2014 at 16:50

1 Answer 1

2

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, i.e. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

this solution is useful to me in bar chart

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.