How to dynamically add rows/columns to a Google Column Chart

后端 未结 3 1029
旧时难觅i
旧时难觅i 2021-01-31 00:27

I want to create a Column Chart , using Google Visualization API , I can send the data to populate the chart\'s DataTable in array form. But I need to generate the chart with va

3条回答
  •  野性不改
    2021-01-31 01:12

    Here's a working solution in jsfiddle.

    Look at the following function. This iterates over an array of data and updates the chart:

    // function to update the chart with new data.
          function updateChart() {
    
              dataTable = new google.visualization.DataTable();
    
              var newData = [['Year', 'Sales', 'Expenses' , 'Other'],
                ['2004',  1000,      400     ,  232   ],
                ['2005',  1170,      460    ,  421   ],
                ['2006',  660,       1120    ,  4324  ],
                ['2007',  1030,      540     ,  4234  ],
                ['2008',  1530,      50     ,    234  ]];
    
              // determine the number of rows and columns.
              var numRows = newData.length;
              var numCols = newData[0].length;
    
              // in this case the first column is of type 'string'.
              dataTable.addColumn('string', newData[0][0]);
    
              // all other columns are of type 'number'.
              for (var i = 1; i < numCols; i++)
                dataTable.addColumn('number', newData[0][i]);           
    
              // now add the rows.
              for (var i = 1; i < numRows; i++)
                dataTable.addRow(newData[i]);            
    
              // redraw the chart.
              chart.draw(dataTable, options);        
    
          }
    

提交回复
热议问题