I am trying to draw a simple Google pie chart by creating a dynamic table using JavaScript.
Why my code fails?
var g;
for (g=0; g <3; g++) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Task');
data.addColumn('number', 'Failed');
data.addColumn('number', 'Passed');
data.addRows(1);
data.setCell(0, 0, "Work?");
data.setCell(0, 1, 80);
data.setCell(0, 2, 20);
var chartName = 'piechart'+(g+1);
var chart = new google.visualization.PieChart(document.getElementById(chartName));
chart.draw(data,options);
}
3 pie charts are being drawn on my screen, but they all have one color and one slice, and not 20% 80% like in my code.
Also, I'm not getting any errors on my console.
Are you aiming for something like this? Also if you can, consider using addRows instead of setCell
I think the problem is with your table / data structure.
<script src="https://www.gstatic.com/charts/loader.js"></script> <div id="piechart1"></div> <div id="piechart2"></div> <div id="piechart3"></div> <script> // Load the Visualization API and the corechart package. google.charts.load('current', { 'packages': ['corechart'] }); // Set a callback to run when the Google Visualization API is loaded. google.charts.setOnLoadCallback(drawChart); function drawChart() { var g; for (g = 0; g < 3; g++) { var data = new google.visualization.DataTable(); data.addColumn('string', 'PassOrfail'); data.addColumn('number', 'Percentage'); data.addRows([ ['Passed', 80], ['Failed', 20], ]); var chartName = 'piechart' + (g + 1); var chart = new google.visualization.PieChart(document.getElementById(chartName)); chart.draw(data); } } </script>
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.