So I have a working google chart that uses a CSV file, parses the CSV data as a string into an array, and uses the array as the datatable.
I actually asked a question and answered it myself Here.
That link will show you a full chunk of code that I used in my full working website.
I intended to just pull the script from the test file and drop it into my website, but now that I've moved it over and included the scripts I needed, I'm getting an error as:
Type Error: $.csv is undefined
Here is the code where $.csv is being utilized (var arrayData), this is a function for drawing the chart
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="jquery.csv.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript"> // load the visualisation API
google.load('visualization', '1', { packages: ['corechart', 'controls'] });
</script>
<script type="text/javascript">
function drawVisualization() {
$.get("Thornton.M2.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
// CAPACITY - En-route ATFM delay - YY - CHART
var crt_ertdlyYY = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'crt_ertdlyYY',
dataTable: data,
options:{
width: 450, height: 160,
title: 'EU-wide en-route ATFM delays (year to date)',
titleTextStyle : {color: 'grey', fontSize: 11},
}
});
crt_ertdlyYY.draw();
});
}
google.setOnLoadCallback(drawVisualization)
</script>
</head>
<body>
<div id="crt_ertdlyYY"></div>
</body>
This example works fully as you can see from the link I had posted before hand, if you wanted to test it. But now that I pull it into my main site the .csv calls do not recognize. I also have 2 other google charts on this page that still work properly so it's isolated to this issue. I'm very new to google charts and pretty confused here!
Related
I have an HTML file where I am uploading a local CSV file and once it has been uploaded I want to use the Google Charts API to generate a chart from that data however I am currently get this error
script.js:29 Uncaught TypeError: Cannot read property 'arrayToDataTable' of undefined
this points to the line in the JavaScript file
var dataDraw = new google.visualization.arrayToDataTable(data);
This is the index.html
<html>
<head>
<meta charset="utf-8" />
<title>CSV to chart</title>
</head>
<body>
<div id="inputs" class="clearfix">
<input type="file" id="files" name="files[]" multiple />
</div>
<hr />
<output id="list">
</output>
<hr />
<table id="contents" style="width:100%; height:400px;" border>
</table>
<div id="chart"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://evanplaice.github.io/jquery-csv/src/jquery.csv.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="script.js"></script>
</body>
</html>
This is the Javascript file
$(document).ready(function() {
$('#files').bind('change', handleFileSelect);
});
function handleFileSelect(evt) {
var files = evt.target.files;
var file = files[0];
printTable(file);
}
function printTable(file) {
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event){
var csv = event.target.result;
var data = $.csv.toArrays(csv);
google.load("visualization", "1", {packages:["corechart"]});
var dataDraw = new google.visualization.arrayToDataTable(data);
var view = new google.visualization.DataView(dataDraw);
view.setColumns([0,1]);
var options = {
title: "CSV Chart",
hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max},
vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max},
legend: 'none'
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart'));
chart.draw(view, options);
console.log("array of data " + data)
var html = '';
for(var row in data) {
html += '<tr>\r\n';
for(var item in data[row]) {
html += '<td>' + data[row][item] + '</td>\r\n';
}
html += '</tr>\r\n';
}
$('#contents').html(html);
};
reader.onerror = function(){ alert('Unable to read ' + file.fileName); };
}
This is the CSV I am uploading.
Temp,Number
69,1
23.5,2
2.3,3
I am having trouble generating a chart from a local CSV file that I am uploading to use with the Google Charts API. I am quite new to using Google Charts so can someone help me understand what I am doing wrong?
Thanks.
there are a couple issues here...
first, the following load statement is incorrect, it is for the old version of google charts.
google.load("visualization", "1", {packages:["corechart"]});
it should be replaced with...
google.charts.load('current', {packages: ['corechart']});
see update library loader code for more info...
next, you need to wait until the load statement has finished,
before using any google chart components,
there are a few ways...
1) you can use the promise the load statement returns.
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
// place chart code here
});
2) use the callback property of the load statement.
google.charts.load('current', {
packages: ['corechart'],
callback: function () {
// place chart code here
}
});
3) use the setOnLoadCallback callback method.
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(function () {
// place chart code here
});
obviously, you can replace any of the above anonymous functions with a named one of your own, e.g.
google.charts.load('current', {
packages: ['corechart'],
callback: drawChart
});
note: arrayToDataTable is a static method, the new keyword is not needed...
var dataDraw = google.visualization.arrayToDataTable(data);
EDIT
if you receive the error...
Data for column(s) axis #0 cannot be of type String
this means the values for the y-axis columns are formatted as strings and not numbers. (columns > 0)
to correct the issue, add a calculated column to the view,
and parse the value as float.
var view = new google.visualization.DataView(dataDraw);
view.setColumns([0, {
calc: function (dt, row) {
return parseFloat(dt.getValue(row, 1));
},
type: 'number',
label: dataDraw.getColumnLabel(1)
}]);
In my page I load the chart as described in the docs. It's a view in asp.net that renders the output. The view checks if a class called Avstemning is populated then puts strings from that class into the chart as data. But if I use Norwegian letters like ø,æ, å. The chart data can't read it even as I specify the language option to use. What is going on here?
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
#if (Model.Avstemning != null)
{
<script type="text/javascript">
google.charts
.load('current', { 'packages': ['corechart'], 'language':'no' });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Avstemning', '#Model.Avstemning.Tittel'],
['#Model.Avstemning.Option1', #Model.Avstemning.One],
['#Model.Avstemning.Option2', #Model.Avstemning.Two],
['#Model.Avstemning.Option3', #Model.Avstemning.Three]
]);
var options = {
title: '#Model.Avstemning.Tittel'};
var chart = new
google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
}
If I change the data variable to take hard coded options with norwegian letters it works. But that's not exactly ideal. Any ideas on how to solve this? Inject javascript from controller?
I solved the encoding issue by using Html.Raw(). Not recommended if these are later to be stored in db, but works for displaying the data as I intended:
var data = google.visualization.arrayToDataTable([
['Avstemning', '#Html.Raw(Model.Avstemning.Tittel)'],
['#Html.Raw(Model.Avstemning.Option1)', #Model.Avstemning.One],
['#Html.Raw(Model.Avstemning.Option2)', #Model.Avstemning.Two],
['#Html.Raw(Model.Avstemning.Option3)', #Model.Avstemning.Three]
]);
var options = {
title: '#Html.Raw(Model.Avstemning.Tittel)',
};
How can I have two google charts on one page? I'm using super proxy to get JSON table from google analytics API.
Currently, only the first chart (Table) is shown. Missing the second chart.
My code is attached below. I'm not so familiar with the API things. I checked some solutions, but all have data locally instead of from online sources, e.g., spreadsheet, JSON table.
Any help would be appreciated.
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript"
src='https://www.google.com/jsapi?autoload={"modules":[{"name":"visualization","version":"1"}]}'>
</script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['table','geochart']});
google.setOnLoadCallback(drawVisualization);
function drawCountriesTable() {
var CountriesTableWrapper = new google.visualization.ChartWrapper({
"containerId": "CountriesTable_div",
"dataSourceUrl": "https://top3dapp.appspot.com/query?id=agpzfnRvcDNkYXBwchULEghBcGlRdWVyeRiAgICAgICACgw&format=data-table-response",
"refreshInterval": 43200,
"chartType": "Table",
"options": {
"showRowNumber" : true
}
});
CountriesTableWrapper.draw();
}
function drawRegionsMap() {
var RegionsMapWrapper = new google.visualization.ChartWrapper({
"containerId": "RegionsMap_div",
"dataSourceUrl": "https://top3dapp.appspot.com/query?id=agpzfnRvcDNkYXBwchULEghBcGlRdWVyeRiAgICAvKGCCgw&format=data-table-response",
"refreshInterval": 43200,
"chartType": "GeoChart",
"options": {
"displayMode": 'markers',
"colorAxis": { "colors": ['#A9DEF2', '#048DC7'] }
}
});
RegionsMapWrapper.draw();
}
function drawVisualization() {
drawCountriesTable();
drawRegionsMap();
}
</script>
</head>
<body>
<h2>Countries</h2>
<div id="CountriesTable_div" style="margin:auto;width:630px;"></div>
<h2>Regions</h2>
<div id="RegionsMap_div" style="margin:auto;width:630px;"></div>
</body>
The is a bug of super proxy. Bug report see:
https://github.com/googleanalytics/google-analytics-super-proxy/issues/17
Following the steps as suggested on github:
Open query_helper.py
Go to the method 'GetPublicEndpointResponse'
In line 395, you should see
transformed_response_content = response.get('transformed_content')
Change that line to:
transformed_response_content = transform.Transform(response_content)
Test/Deploy updates
Here is my code which is right as per my knowledge. Because I created similar PIE chart successfully,
Error is : Unknown Header Type : 24
I think error is in parsing data from csv file. But it parsed correctly in string & int form.
Can someone tell what is the issue here.
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="http://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["gauge"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
// grab the CSV
$.get("Chart2-data.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
//alert(arrayData);
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
// this view can select a subset of the data at a time
var view = new google.visualization.DataView(data);
view.setColumns([0,1]);
// set chart options
var options = {
title: "A Chart from a CSV!",
hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max},
vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max},
legend: 'none'
};
var chart = new google.visualization.Gauge(document.getElementById('gauge'));
chart.draw(data, options);
});
}
</script>
</head>
<body>
<div id="gauge" style="width: 900px; height: 500px;"></div>
</body>
</html
>
csv data:
Engine,24
min,34
max,0
yellowFrom,10
yellowTo,6
redFrom,6
redTo,0
I was having the same problem.
Using Firebug on my DB result I was able to identify that the problem was that the google library threating a numeric value as an array header.
My array is the following
[['234 234 - ',234.00],['234 234 - ',234.00],['cuarta zzzzzzzzz prueba htmlzzzzzzz - ',654999.00],['fulanita de tal - ',150.00],['fulanita de tal - ',133.00],['Mario Alvarez Alvarez - tony',125143.20],['otra5555 prueba5555 - ',1866.00],['prieba de insert actualizando - ',1101.00],['prueba 888 - ',987.00],['prueba con html - ',854.00],['prueba de guardado - ',123.00],['prueba de insert - ',369.00],['prueba insert actualizando 02 - ',753.00],['prueba666 7777 - ',1547.00],['prueba666 7777 - ',1547.00],['prueba88888 de guardado8888 - ',1576.00],['tercera prueba - ',98765.00]]
My javascript error was:
Error: Unknown header type: 234
The solution is explained in the Google Visualization API Reference:
google.visualization.arrayToDataTable(twoDArray, opt_firstRowIsData)
Check this link for detailed info
You have to explicit tell the library that the first row is data, not a header. I add the second parameter true like this:
var data = google.visualization.arrayToDataTable(vArray, true);
PD: My web app was working fine until a few days ago. I guess google did some change to the library.
Hope my explain will help you
Here is my code to create google chart from csv data. ANd also no error. But even chart does not appear.
Here is the documentation for which works: http://economistry.com/2013/07/easy-data-visualization-with-google-charts-and-a-csv/
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="http://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
// grab the CSV
$.get("Chart1-data.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
alert(arrayData);
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
// this view can select a subset of the data at a time
var view = new google.visualization.DataView(data);
view.setColumns([0,1]);
// set chart options
var options = {
title: "A Chart from a CSV!",
hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max},
vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max},
legend: 'none'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
});
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
Chart1-data.csv
Category,
A,34
B,23
C,14
D,57
E,18
Other,5
Do I missing anything in the code?
Good news: Your Code is fine! Your CSV file is the bottleneck.
Column names can't be null, means Category, => Category,''
No additional line breaks between data rows, means
A,34
B,23
=>
A,34
B,23
Result:
Category,''
A,34
B,23
C,14
D,57
E,18
Other,5
That is all! :)
There doesn't seem any kind of problem with this Google chart code snippet.
Though in browser console there are some Uncaught JavaScript errors.
Most importantly there is
" Uncaught null "error which is in reference to blank space after "Category" so Category, ' ' should work fine