Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Google Chart data table array from two arrays

I'm trying to use Google's chart api: https://google-developers.appspot.com/chart/interactive/docs/gallery/columnchart

I have two arrays that I'd like to use to generate and label the visualization. However, I can't find a way to combine and convert these arrays into the proper object structure.

My arrays are the following and their contents are next to them:

years;   // 2014,2015,2020,2021
sales;   // 100,100,200,100

I need to dynamically use these arrays to form this object, which is in the format that Google's API uses:

 var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales'],
          ['2014',  100],
          ['2015',  100],
          ['2020',  200],
          ['2021',  100]
        ]);

Thank you for any help.

like image 966
Rob Avatar asked Apr 07 '13 23:04

Rob


People also ask

What is arrayToDataTable?

arrayToDataTable()This helper function creates and populates a DataTable using a single call. Advantages: Very simple and readable code executed in the browser. You can either explicitly specify the data type of each column, or let Google Charts infer the type from the data passed in.

What is Google API in data visualization?

The Google Chart API is an extremely simple tool that lets you easily create a chart from some data and embed it in a webpage. You embed the data and formatting parameters in an HTTP request, and Google returns a PNG image of the chart.


1 Answers

You should use addColumn and addRow in a for loop to go through your arrays.

Here is a sample:

function drawVisualization() {
  // Create and populate the data table.
  var years = ['2001', '2002', '2003', '2004', '2005'];
  var sales = [1, 2, 3, 4, 5];

  var data = new google.visualization.DataTable();
  data.addColumn('string', 'years');
  data.addColumn('number', 'sales');

  for(i = 0; i < years.length; i++)
    data.addRow([years[i], sales[i]]);

  // Create and draw the visualization.
  new google.visualization.LineChart(document.getElementById('visualization')).
    draw(data, {});
}
like image 137
jmac Avatar answered Nov 14 '22 06:11

jmac