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.
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.
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.
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, {});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With