Insert dynamic data into a Google Pie Chart

I have a task to insert dynamic data into Google PieChart.

Playground

In this link, I insert this code:

function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.DataTable();

var mycars=["Saab","Volvo","BMW"];
var mypoints=[4,12,45];

data.addColumn('string', 'Cars');
data.addColumn('number', 'Numbers'); 
data.addRows(mycars.length);
for  (var i = 0; i < mycars.length; i++){
  data.setCell(i,0,mycars[i]);
  data.setCell(i,1,mypoints[i]);
}
// Create and draw the visualization.
new google.visualization.PieChart(document.getElementById('visualization')).
draw(data, {title:"So, how was your day?"});
}

In the following example, I get dynamic arrays mycarsand mypointsthen I try to insert these arrays into the diagram inside for loop.

PieChart is not displayed. What's wrong with it?

+5
source share
2 answers

You have a javascript error. You need to use the keyword newwhen creating the DataTable instance.

Replace

var data = google.visualization.DataTable();

with

var data = new google.visualization.DataTable();
+3
source

I solved the problem using code in jquery as follows:

$("#piechart_3d").show();
google.load("visualization", "1", {
    packages: ["corechart"], callback: function () {
        var data = google.visualization.arrayToDataTable([
                        ['Going', 'a Day'],
                        ['Car', 11],
                        ['Bus', 2],
                        ['Moto', 2]
                    ]);
        var options = {
                        title: 'Report',
                        backgroundColor: 'transparent',
                        is3D: true,
                    };

        var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
        chart.draw(data, options);
    }
});
0
source

All Articles