How To Display Multiple Charts In Loop 2020

Let's Display Charts single chart and then multiple charts using loop. We are going to use google charts to achieve this.


Step by step explained Video guide

Printing Single Chart

 //ADD DIV IN HTML
<div align="center">
     <div id="piechart"></div>
</div>

Now we can add code to generate chart. Have a look

 //INCLUDING REQUIRED JS USING CDN
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<script type="text/javascript">
// Load google charts
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);

// Draw the chart and set the chart values
function drawChart() {
    var data = google.visualization.arrayToDataTable([
                      ['Day', 'Income'],
                      ['Sunday', 800],
                      ['Monday', 500],
                      ['Tuesday', 690],
                      ['Wednesday', 467],
                      ['Friday', 890]
                    ]);

// Optional add a title and set the width and height of the chart
   var options = {
          'title':'Income Day Wise',
          'width':550, 
          'height':400
   };

// Display the chart inside the <div> element with id="piechart"
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
   chart.draw(data, options);
}
 </script>

In above code we are passing array of data. We have to pass data in this format as an array so google charts can display it as we want. Option variable is Optional but useful. Above chart code will output something like this.

Now what if you want to print multiple charts on same div tag. In that case we can use loop. First we add a div.

Appending Multiple Chart On Same Div

 <div align="center">
       <div id="draw-charts"></div>
</div>

And then we append charts on that div. Have a look.

 <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
        google.charts.load('current', {
		callback: function () {
		var data = new google.visualization.DataTable();
			data.addColumn('string', 'Topping');
			data.addColumn('number', 'Slices');
			data.addRows([
				['Day', 0],
				['Sunday', 800],
				['Monday', 500],
				['Tuesday', 690],
				['Wednesday', 467],
				['Friday', 890]
			]);
                var options = {
			title:'Income Day Wise',
			width:400,
			height:300
		};

            for (var i = 0; i < 6; i++) {
		var container = document.getElementById('draw-charts').appendChild(document.createElement('div'));
		var chart = new 
google.visualization.PieChart(container);
                chart.draw(data, options);
                }
           },
            packages: ['corechart']
});
</script>

Multiple charts with dynamic data. Each Chart With Different Data

Now we want to print multiple charts, But each chart should be different based on dynamic data. have a look

So we start with adding a div.

 <div align="center">
    <div id="draw-charts"></div>
</div>

Now the code with different array data for each chart.

 <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
             let weekOne = [
                               ['Week', 1],
                               ['Sunday', 800],
                               ['Monday', 500],
                               ['Tuesday', 690],
                               ['Wednesday', 467],
                               ['Friday', 890]
                           ];
              let weekTwo = [
                               ['Week', 2],
                               ['Sunday', 340],
                               ['Monday', 670],
                               ['Tuesday', 620],
                               ['Wednesday', 497],
                               ['Friday', 290]
                            ];
             let weekThree = [
                               ['Week', 3],
                               ['Sunday', 540],
                               ['Monday', 234],
                               ['Tuesday', 520],
                               ['Wednesday', 297],
                               ['Friday', 990]
                             ];
              //MAKING FINAL ARRAY FOR CHARTS
              let weeksData = [weekOne,weekTwo,weekThree]
  //LOOPING THROUGH ARRAY TO PRINT CHART
  for(let r=0; r<weeksData.length; r++){
      //ADDING DIV TAGS DYNAMICALLY SO CHARTS CAN BIND ON THEM
      $("#draw-charts").append('<div id="draw-charts'+r+'"></div>');
          //r changes each loop
           google.charts.load('current', {
               callback: function () {
               var data = new google.visualization.DataTable();
               data.addColumn('string', 'Topping');
               data.addColumn('number', 'Slices');
               //PASSING CHART DATA IN LOOP
               data.addRows(weeksData[r]);
               var options = {
                    title:"Let's Print Graphs From Loop Dynamic data",
                    width:400,
                    height:300
               };
//BINDING CHARTS WITH DYNAMIC DIV TAGS 
var container = document.getElementById('draw-charts'+r).appendChild(document.createElement('div'));
var chart = new google.visualization.PieChart(container);
   chart.draw(data, options);
},
packages: ['corechart']
});
}
</script>

Now we have array of 3 different arrays. You need to arrange your data something like this. We are appending div element into the DOM dynamically and then attaching each chart on each div.

Notice "r" changes in each loop so we get saperate divs and charts. And we are passing chart data using "r". Check these lines.

 //ADDING DIV TAGS DYNAMICALLY SO CHARTS CAN BIND ON THEM
$("#draw-charts").append('<div id="draw-charts'+r+'"></div>');

//PASSING CHART DATA IN LOOP
data.addRows(weeksData[r]);

//BINDING CHARTS WITH DYNAMIC DIV TAGS 
var container = document.getElementById('draw-charts'+r).appendChild(document.createElement('div'));

Output should look something like this.