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
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)
}]);
I've got the below script & it's working perfectly.
However, it may be the case that on some days there are no orders. In this case, the date should still show, but the value should be zero.
Like in the above, it jumps from 06-19 to 06-21.
Is there a way to still show 06-20 and just have the value as zero? The missing date doesn't exist in the database as a record is only created when an expense is submitted, so I'm a bit lost.
Thank you in advance
Head Script
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'Total Orders'],
['2017-9-6',200],['2017-8-6',1500],['2017-7-7',800],['2017-7-3',1,800],['2017-7-2',200],['2017-6-13',10000],['2017-10-5',800],['2017-10-12',4,500],['',],
]);
var options = {
title: 'Orders Per Day'
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart"));
chart.draw(data, options);
}
</script>
Body Script
<h3>Column Chart</h3>
<div id="columnchart" style="width: 900px; height: 500px;"></div>
To address this issue you would need to define that your axes are continuous. This can be achieved by defining the data type for your chart columns.
Below is an example that uses different data to your problem to make it easier to see the solution. The string dates in the array need to be converted to a date object to meet the data type criteria. This is achieved by using the new Date() object.
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Total Orders');
data.addRows([
[new Date('2017-9-6'),200],
[new Date('2017-7-7'),800],
[new Date('2017-7-3'),800],
[new Date('2017-7-2'),200],
[new Date('2017-6-13'),300]
]);
var options = {
title: 'Orders Per Day'
};
var chart = new
google.visualization.ColumnChart(document.getElementById('columnchart'));
chart.draw(data, options);
}
</script>
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!
Below is the code I have for displaying the Chart . I am unsure as to what is going wrong here.
Please bear with me , this is the first time I have asked a question in this forum.
Thank you for your help
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(DrawChart);
function DrawChart() {
var data = google.visualization.arrayToDataTable([
['Short Shipment', 'Product Questions', 'Product Service Request', 'Billing Question','Product Issue','Return or Exchange Request','- None -'],
[1, 3, 4, 8, 8, 11, 283]]);
var options = {
chart: {
title: 'Case Issue Summary'
},
bars: 'horizontal'
};
var chart = new google.charts.Bar(document.getElementById('BarChartCase'));
chart.draw(data, options);
}
</script>
</head>
<body padding="0.5in 0.5in 0.5in 0.5in" size="Letter">
<div id="BarChartCase" style="width: 200px; height: 100px;"> </div>
</body>
</html>
Your code is 99/100 copied from developers.google.com/chart/....
The only changes you made is the width and height to 200 and 100.
Change it to a greater number and you'll be able to see your bar chart.
codepen copy
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