"Table has no rows" Error in Google Charts Histogram - google-visualization

I am working with Google Histogram chart. It working fine with some data sets but not for other data sets. And it raise an error "Table has no rows" even my input is correct.
Here i am reading a csv file column wise and pass to visualization page.
for eg: I am reading 2 csv column here and passing to visualization page. Here my input to Google histogram is
var inputdata1 = [["val","d"],["val","2"],["val","2"],["val","1"],["val","2"],["val","2"],["val","1"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","1"],["val","2"]];
and this working fine and gives histogram for me.
while I am passing other 2 columns.Here my input to Google histogram is
var inputdata2 = [["val","b"],["val","3"],["val","3"],["val","3"],["val","5"],["val","1"],["val","12"],["val","7"],["val","11"],["val","1"],["val","7"],["val","6"],["val","16"],["val","11"],["val","21"],["val","12"],["val","1"],["val","22"],["val","16"],["val","1"],["val","21"],["val","11"],["val","6"],["val","11"],["val","15"],["val","12"],["val","12"]];
while executing this, it raise an error that "Table has no rows" . Please check my fiddle.
Any help would be greatly appreciated.
Thank you in Advance.

In fact neither inputdata1 nor inputdata2 contain JSON data that are supported by histogram chart.
According to the documentation the following formats are supported:
Data Format
There are two ways to populate a histogram datatable. When there's
only one series:
var data = google.visualization.arrayToDataTable([
['Name', 'Number'],
['Name 1', number1],
['Name 2', number2],
['Name 3', number3],
...
]);
...and when there are multiple series:
var data = google.visualization.arrayToDataTable([
['Series Name 1', 'Series Name 2', 'Series Name 3', ...],
[series1_number1, series2_number1, series3_number1, ...],
[series1_number2, series2_number2, series3_number2, ...],
[series1_number3, series2_number3, series3_number3, ...],
...
]);
Having said that you might want to convert the second column into number format:
var inputJson = [["val","b"],["val","3"],["val","3"],["val","3"],["val","5"],["val","1"],["val","12"],["val","7"],["val","11"],["val","1"],["val","7"],["val","6"],["val","16"],["val","11"],["val","21"],["val","12"],["val","1"],["val","22"],["val","16"],["val","1"],["val","21"],["val","11"],["val","6"],["val","11"],["val","15"],["val","12"],["val","12"]];
var chartJson = inputJson.map(function(item,i){
if(i == 0)
return item;
else {
return [item[0],parseInt(item[1])];
}
});
var data = google.visualization.arrayToDataTable(chartJson);
Once the data is converted the chart will be rendered properly.
Working example
google.load('visualization', '1.1', {
'packages': ['corechart']
});
google.setOnLoadCallback(drawStuff);
function drawStuff() {
var inputJson = [["val","b"],["val","3"],["val","3"],["val","3"],["val","5"],["val","1"],["val","12"],["val","7"],["val","11"],["val","1"],["val","7"],["val","6"],["val","16"],["val","11"],["val","21"],["val","12"],["val","1"],["val","22"],["val","16"],["val","1"],["val","21"],["val","11"],["val","6"],["val","11"],["val","15"],["val","12"],["val","12"]];
var chartJson = inputJson.map(function(item,i){
if(i == 0)
return item;
else {
return [item[0],parseInt(item[1])];
}
});
var data = google.visualization.arrayToDataTable(chartJson);
//The below input data works fine.
//var data = google.visualization.arrayToDataTable([["val","d"],["val","2"],["val","2"],["val","1"],["val","2"],["val","2"],["val","1"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","1"],["val","2"]]);
// Set chart options
var options = {
width: 400,
height: 300,
histogram: {
bucketSize: 0.1
}
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.Histogram(document.getElementById('chart_div'));
chart.draw(data, options);
};
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script src="chart.js"></script>
<div id="chart_div"></div>

Related

Google charts error:every row given must be either null or an array

I am working on a website that is intended to show some basic Google charts. The data comes from a text file that i retrieve through Ajax. It's got a x, y value and an annotation field. The data looks like this:
[[-0.8, -0.47, "100-005-10"],
[-0.7, -0.46, "100-005-9"],
[-0.6, -0.45, "100-005-8"],
[-0.5, -0.44, "100-005-7"]]
Here's my code:
<script >
var xmlhttp = new XMLHttpRequest();
var array;
xmlhttp.onreadystatechange = function() {
array = this.responseText;
};
xmlhttp.open("GET", "array.array", true);
xmlhttp.send();
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable($.parseJSON(array), true)
data.addColumn('number', 'x');
data.addColumn('number', 'y');
data.addColumn({type: 'string', role: 'annotation'});
data.addRow(array);
var options = {
legend: 'none',
colors: ['#087037'],
selectionMode: 'single',
tooltip: {trigger: 'selection'},
pointSize: 12,
animation: {
duration: 200,
easing: 'inAndOut',
}
};
var chart = new google.visualization.ScatterChart(document.getElementById('animatedshapes_div'));
chart.draw(data, options);
}
</script>
When i run the code, i get this error message:
Error: If argument is given to addRow, it must be an array, or null
I just don't know how to transform the plain text from the ajax response to an array.
try using JSON.parse to convert the string to an actual array...
data.addRows(JSON.parse(array));
In one of the case, need to add Square brackets []
self.tableValues.forEach((row: any) => {
if(row) {
dataTable.addRows([row]); // <-- row is array; so try [row]
}
});

How may I explicitly define the datatype of a Google Charts DataTable column after it has been created?

I am using jquery-csv toArrays function to populate a google visualization DataTable like this:
function drawChart() {
// Load the CSV file into a string
$.get("Book1.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
// Create new DataTable object from 2D array
var data = new google.visualization.arrayToDataTable(arrayData);
// Set which columns we will be using
var view = new google.visualization.DataView(data);
view.setColumns([0,1,5,9,13,17,21,25,29]);
...
The first column in the CSV file contains a list of times which are used as the horizontal axis for the chart.
Google visualization's arrayToDataTable function attempts to automatically determine the appropriate data type for each column but it fails with the first column assigning it the String type instead of the required TimeOfDay type.
I know I can determine a columns datatype when populating it manually like so:
var dt = new google.visualization.DataTable({
cols: [{id: 'time', label: 'Time', type: 'timeofday'},
{id: 'temp', label: 'Temperature', type: 'number'}],
...
But can I change a column's data type after it has already been populated by the arrayToDataTable function?
EDIT:
Here is a CSV file similar to those which I'm currently using.
When I change the column heading to object notation before creating the DataTable as suggested below and force it to TimeOfDay, the first column gets converted to a series of NaN:NaN:NaN.NaN. Here is a simplified example similar to the one in the suggested answer.
google.load('visualization', '1', {packages: ['controls', 'charteditor']});
google.setOnLoadCallback(drawChart);
function drawChart() {
// Load the CSV file into a string
$.get("Book1.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
// Create new DataTable object from 2D array
var data = new google.visualization.arrayToDataTable(arrayData);
// Show datatable in grid to see what is happening before the data type change
var chart1 = new google.visualization.Table(document.getElementById('chart_div0'));
chart1.draw(data);
// Here we explicitly define type of first column in table
arrayData[0][0] = {type: 'timeofday', label: arrayData[0][0]};
// Create new DataTable object from 2D array
var data = new google.visualization.arrayToDataTable(arrayData);
// Show datatable in grid to see what is happening after the data type change
var chart2 = new google.visualization.Table(document.getElementById('chart_div1'));
chart2.draw(data);
});
}
Thanks!
change the column heading to object notation before creating the DataTable
and use a DataView to convert the first column to 'timeofday'
google.charts.load('current', {
callback: function () {
csvString = 'TIME,TEMP0,HUM0\n12:00:04 AM,24.7,50\n12:01:05 AM,24.7,50';
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
var data = new google.visualization.arrayToDataTable(arrayData);
var columns = [];
for (var i = 0; i < data.getNumberOfColumns(); i++) {
columns.push(i);
}
var view = new google.visualization.DataView(data);
columns[0] = {
calc: function(dt, row) {
var thisDate = new Date('1/1/2016 ' + dt.getValue(row, 0));
return [thisDate.getHours(), thisDate.getMinutes(), thisDate.getSeconds(), thisDate.getMilliseconds()];
},
label: arrayData[0][0],
type: 'timeofday'
};
view.setColumns(columns);
var chart = new google.visualization.Table(document.getElementById('chart_div'));
chart.draw(view);
},
packages: ['corechart', 'table']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<div id="chart_div"></div>

google chart api material date month

I have a google bar chart with multiple series and a date hAxis.
My problem is that i want to show months only, but i get the label multiple times.
Here's an example
google.charts.load('current', {'packages': ['bar'], 'language': 'de'});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var chart;
var chartDiv = document.getElementById('test');
var data = new google.visualization.DataTable('{"cols":[{"type":"date","pattern":""},{"type":"number"},{"type":"number"},{"type":"number"},{"type":"number"},{"type":"number"},{"type":"number"},{"type":"number"}],"rows":[{"c":[{"v":"Date(2016,2,1)"},{"v":2030,"f":"2030 km"},{"v":2098,"f":"2098 km"},{"v":1352,"f":"1352 km"},{"v":4412,"f":"4412 km"},{"v":132,"f":"132 km"},{"v":2435,"f":"2435 km"},{"v":3952,"f":"3952 km"}]},{"c":[{"v":"Date(2016,3,1)"},{"v":3177,"f":"3177 km"},{"v":2901,"f":"2901 km"},{"v":2491,"f":"2491 km"},{"v":1480,"f":"1480 km"},{"v":2272,"f":"2272 km"},{"v":400,"f":"400 km"},{"v":1096,"f":"1096 km"}]}]}');
var options = {
legend: { position: 'none' },
hAxis: {
type: 'category',
format: 'MMMM'
}
};
chart = new google.charts.Bar(chartDiv);
chart.draw(data, google.charts.Bar.convertOptions(options));
}
https://jsfiddle.net/1Lusd06n/3/
If i shrink the width of the fiddle, the month names are grouped and displayed once but this does not happen if there is more space.

merge total of Stacked Bar Chart

I have two unsigned integers per bar: X and Y.
X is always less than Y because it is a subset of it.
I want to combine these two values into a single bar. However, the Stacking Bar Chart adds up the values instead of "overlapping" them.
This is what isStacked: true results in:
XXXYYYYY
(3x + 5y, Axis goes up to 8)
And here is what my goal is:
XXXYY
(3x within 5y, Axis goes up to 5)
How can I "merge" the values into one bar that is based on Y only and thus doesn't impact the axis' maximum value?
the data will need to be adjusted, setting chart options won't get it.
you could create a view, add a calculated column, and exclude the original Y...
google.charts.load('current', {
packages: ['corechart'],
callback: drawChart
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'X', 'Y'],
['2016', 3, 5]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: function (data, row) {
return {
v: data.getValue(row, 2) - data.getValue(row, 1),
f: data.getValue(row, 2).toString()
};
},
type: 'number',
label: 'Y'
}]);
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(view, {isStacked: true});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

How to show an Empty Google Chart when there is no data?

Consider drawing a column chart and I don't get any data from the data source, How do we draw an empty chart instead of showing up a red colored default message saying "Table has no columns"?
What I do is initialize my chart with 1 column and 1 data point (set to 0). Then whenever data gets added I check if there is only 1 column and that it is the dummy column, then I remove it. I also hide the legend to begin so that it doesn't appear with the dummy column, then I add it when the new column gets added.
Here is some sample code you can plug in to the Google Visualization Playground that does what I am talking about. You should see the empty chart for 2 seconds, then data will get added and the columns will appear.
var data, options, chart;
function drawVisualization() {
data = google.visualization.arrayToDataTable([
['Time', 'dummy'],
['', 0],
]);
options = {
title:"My Chart",
width:600, height:400,
hAxis: {title: "Time"},
legend : {position: 'none'}
};
// Create and draw the visualization.
chart = new google.visualization.ColumnChart(document.getElementById('visualization'));
chart.draw(data,options);
setTimeout('addData("12:00",10)',2000);
setTimeout('addData("12:10",20)',3000);
}
function addData(x,y) {
if(data.getColumnLabel(1) == 'dummy') {
data.addColumn('number', 'Your Values', 'col_id');
data.removeColumn(1);
options.legend = {position: 'right'};
}
data.addRow([x,y]);
chart.draw(data,options);
}​
A even better solution for this problem might be to use a annotation column instead of a data column as shown below. With this solution you do not need to use any setTimeout or custom function to remove or hide your column. Give it a try by pasting the given code below into Google Code Playground.
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['', { role: 'annotation' }],
['', '']
]);
var ac = new google.visualization.ColumnChart(document.getElementById('visualization'));
ac.draw(data, {
title : 'Just a title...',
width: 600,
height: 400
});
}
​
The way I did this was by disabling the pie slices, turning off tooltips, stuffing in a pretend value and making it gray. I'm sure there are more clever ways to do this, but this worked for me where the other methods didn't.
The only drawback is that it sets both items in the legend to gray as well. I think you could perhaps just add a third item, and make it invisible on the legend only. I liked this way though.
function drawChart() {
// Define the chart to be drawn.
data = new google.visualization.DataTable();
data.addColumn({type: 'string', label: 'Result'});
data.addColumn({type: 'number', label: 'Count'});
data.addRows([
['Value A', 0],
['Value B', 0]
]);
var opt_pieslicetext = null;
var opt_tooltip_trigger = null;
var opt_color = null;
if (data.getValue(1,1) == 0 && data.getValue(0,1) == 0) {
opt_pieslicetext='none';
opt_tooltip_trigger='none'
data.setCell(1,1,.1);
opt_color= ['#D3D3D3'];
}
chart = new google.visualization.PieChart(document.getElementById('mydiv'));
chart.draw(data, {sliceVisibilityThreshold:0, pieSliceText: opt_pieslicetext, tooltip: { trigger: opt_tooltip_trigger }, colors: opt_color } );
}