Google Visualization BarFormat - google-visualization

Hi I am trying to use two different foramtters for my DataTable. They get the base value from two different text input fields.
The ArrowFormatter is working, but how can I refresh the base value if the user changes the input in the text field?
and the Barformatter doesn´t work. It only shows html code in the table.
var formatterEnergy = new google.visualization.ArrowFormat({
base: document.getElementById("energy_input").value,
allowHtml: true,
});
formatterEnergy.format(data, 3);
var formatterPower = new google.visualization.BarFormat({
base: document.getElementById("power_input").value,
allowHtml: true,
});
formatterPower.format(data, 6);
var view = new google.visualization.DataView(data);
var drawOptions = {
showRowNumber: false,
allowHtml: true,
};

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>

"Table has no rows" Error in Google Charts Histogram

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>

How to dynamically add and remove views with Ember.js

I am trying to create an interface for traversing tables in a relation database. Each select represents a column. If the column is a foreign key, a new select is added to the right. This keeps happening for every foreign key that the user accesses. The number of selects is dynamic.
I made a buggy implementation that has code that manually adds and removes select views. I think it probably can be replaced with better Ember code (some kind of array object maybe?), I'm just not sure how to best use the framework for this problem.
Here's my JSBin http://jsbin.com/olefUMAr/3/edit
HTML:
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Ember template" />
<meta charset=utf-8 />
<title>JS Bin</title>
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script src="http://builds.emberjs.com/handlebars-1.0.0.js"></script>
<script src="http://builds.emberjs.com/tags/v1.1.2/ember.js"></script>
</head>
<body>
<script type="text/x-handlebars" data-template-name="my_template">
{{view fieldSelects}}
</script>
<div id="main"></div>
</body>
</html>
JavaScript:
App = Ember.Application.create();
var TemplatedViewController = Ember.Object.extend({
templateFunction: null,
viewArgs: null,
viewBaseClass: Ember.View,
view: function () {
var controller = this;
var viewArgs = this.get('viewArgs') || {};
var args = {
template: controller.get('templateFunction'),
controller: controller
};
args = $.extend(viewArgs, args);
return this.get('viewBaseClass').extend(args);
}.property('templateFunction', 'viewArgs'),
appendView: function (selector) {
this.get('view').create().appendTo(selector);
},
appendViewToBody: function () {
this.get('view').create().append();
}
});
var DATA = {};
DATA.model_data = {
"Book": {
"fields": [
"id",
"title",
"publication_year",
"authors"
],
"meta": {
"id": {},
"title": {},
"publication_year": {},
"authors": {
"model": "Author"
}
}
},
"Author": {
"fields": [
"id",
"first_name",
"last_name",
"books"
],
"meta": {
"id": {},
"first_name": {},
"last_name": {},
"books": {
"model": "Book"
}
}
}
};
var Controller = TemplatedViewController.extend({
view: function () {
var controller = this;
return this.get('viewBaseClass').extend({
controller: controller,
templateName: 'my_template'
});
}.property(),
selectedFields: null,
fieldSelects: function () {
var filter = this;
return Ember.ContainerView.extend({
controller: this,
childViews: function () {
var that = this;
var selectedFields = filter.get('selectedFields');
var ret = [];
var model = 'Book';
selectedFields.forEach(function (item, index, enumerable) {
var selection = item;
if (model) {
var select = that.makeSelect(model, that.getPositionIndex(), selection, true).create();
ret.pushObject(select);
model = DATA.model_data[model].meta[selection].model;
}
});
return ret;
}.property(),
nextPositionIndex: 0,
incrementPositionIndex: function () {
this.set('nextPositionIndex', this.get('nextPositionIndex') + 1);
},
getPositionIndex: function () {
var index = this.get('nextPositionIndex');
this.incrementPositionIndex();
return index;
},
setNextPositionIndex: function (newValue) {
this.set('nextPositionIndex', newValue+1);
},
makeSelect: function (modelName, positionIndex, selection, isInitializing) {
var view = this;
return Ember.Select.extend({
positionIndex: positionIndex,
controller: filter,
content: DATA.model_data[modelName].fields,
prompt: '---------',
selection: selection || null,
selectionChanged: function () {
var field = this.get('selection');
// Remove child views after this one
var lastIndex = view.get('length') - 1;
if (lastIndex > this.get('positionIndex')) {
view.removeAt(this.get('positionIndex')+1, lastIndex-this.get('positionIndex'));
view.setNextPositionIndex(this.get('positionIndex'));
}
if (! isInitializing && DATA.model_data[modelName].meta[field].model) {
var relatedModel = DATA.model_data[modelName].meta[field].model;
view.pushObject(view.makeSelect(relatedModel, view.getPositionIndex()).create());
}
// Reset ``isInitializing`` after the first run
if (isInitializing) {
isInitializing = false;
}
var selectedFields = [];
view.get('childViews').forEach(function (item, index, enumerable) {
var childView = item;
var selection = childView.get('selection');
selectedFields.pushObject(selection);
});
filter.set('selectedFields', selectedFields);
}.observes('selection')
});
}
});
}.property()
});
var controller = Controller.create({
selectedFields: ['authors', 'first_name']
});
$(function () {
controller.appendView('#main');
});
Approach:
I would tackle this problem using an Ember Component.
I have used a component because it will be:
Easily reusable
The code is self contained, and has no external requirements on any of your other code.
We can use plain javascript to create the view. Plain javascript should make the code flow easier to understand (because you don't have to know what Ember is doing with extended objects behind the scenes), and it will have less overhead.
Demo:
I have created this JSBin here, of the code below.
Usage
Add to your handlebars template:
{{select-filter-box data=model selected=selected}}
Create a select-filter-box tag and then bind your model to the data attribute, and your selected value array to the selected attribute.
The application:
App = Ember.Application.create();
App.ApplicationController = Ember.ObjectController.extend({
model: DATA.model_data,
selected: ['Author','']
});
App.SelectFilterBoxComponent = Ember.Component.extend({
template: Ember.Handlebars.compile(''), // Blank template
data: null,
lastCount: 0,
selected: [],
selectedChanged: function(){
// Properties required to build view
var p = this.getProperties("elementId", "data", "lastCount", "selected");
// Used to gain context of controller in on selected changed event
var controller = this;
// Check there is at least one property. I.e. the base model.
var length = p.selected.length;
if(length > 1){
var currentModelName = p.selected[0];
var type = {};
// This function will return an existing select box or create new
var getOrCreate = function(idx){
// Determine the id of the select box
var id = p.elementId + "_" + idx;
// Try get the select box if it exists
var select = $("#" + id);
if(select.length === 0){
// Create select box
select = $("<select id='" + id +"'></select>");
// Action to take if select is changed. State is made available through evt.data
select.on("change", { controller: controller, index: idx }, function(evt){
// Restore the state
var controller = evt.data.controller;
var index = evt.data.index;
var selected = controller.get("selected");
// The selected field
var fieldName = $(this).val();
// Update the selected
selected = selected.slice(0, index);
selected.push(fieldName);
controller.set("selected", selected);
});
// Add it to the component container
$("#" + p.elementId).append(select);
}
return select;
};
// Add the options to the select box
var populate = function(select){
// Only populate the select box if it doesn't have the correct model
if(select.data("type")==currentModelName)
return;
// Clear any existing options
select.html("");
// Get the field from the model
var fields = p.data[currentModelName].fields;
// Add default empty option
select.append($("<option value=''>------</option>"));
// Add the fields to the select box
for(var f = 0; f < fields.length; f++)
select.append($("<option>" + fields[f] + "</option>"));
// Set the model type on the select
select.data("type", currentModelName);
};
var setModelNameFromFieldName = function(fieldName){
// Get the field type from current model meta
type = p.data[currentModelName].meta[fieldName];
// Set the current model
currentModelName = (type !== undefined && type.model !== undefined) ? type.model : null;
};
// Remove any unneeded select boxes. I.e. where the number of selects exceed the selected length
if(p.lastCount > length)
for(var i=length; i < p.lastCount; i++)
$("#" + p.elementId + "_" + i).remove();
this.set("lastCount", length);
// Loop through all of the selected, to build view
for(var s = 1; s < length; s++)
{
// Get or Create select box at index s
var select = getOrCreate(s);
// Populate the model fields to the selectbox, if required
populate(select);
// Current selected
var field = p.selected[s];
// Ensure correct value is selected
select.val(field);
// Set the model for next iteration
setModelNameFromFieldName(field);
if(s === length - 1 && type !== undefined && type.model !== undefined)
{
p.selected.push('');
this.notifyPropertyChange("selected");
}
}
}
}.observes("selected"),
didInsertElement: function(){
this.selectedChanged();
}
});
How it works
The component takes the two parameters model and selected then binds an observer onto the selected property. Any time the selection is changed either through user interaction with the select boxes, or by the property bound to selected the view will be redetermined.
The code uses the following approach:
Determine if the selection array (selected) is greater than 1. (Because the first value needs to be the base model).
Loop round all the selected fields i, starting at index 1.
Determine if select box i exists. If not create a select box.
Determine if select box i has the right model fields based on the current populated model. If yes, do nothing, if not populate the fields.
Set the current value of the select box.
If we are the last select box and the field selected links to a model, then push a blank value onto the selection, to trigger next drop down.
When a select box is created, an onchange handler is hooked up to update the selected value by slicing the selected array right of the current index and adding its own value. This will cause the view to change as required.
A property count keeps track of the previous selected's length, so if a change is made to a selection that decreases the current selected values length, then the unneeded select boxes can be removed.
The source code is commented, and I hope it is clear, if you have any questions of queries with how it works, feel free to ask, and I will try to explain it better.
Your Model:
Having looked at your model, have you considered simplifying it to below? I appreciate that you may not be able to, for other reasons beyond the scope of the question. Just a thought.
DATA.model_data = {
"Book": {
"id": {},
"title": {},
"publication_year": {},
"authors": { "model": "Author" }
},
"Author": {
"id": {},
"first_name": {},
"last_name": {},
"books": { "model": "Book" }
}
};
So field names would be read off the object keys, and the value would be the meta data.
I hope you find this useful. Let me know if you have any questions, or issues.
The Controller:
You can use any controller you want with this component. In my demo of the component I used Ember's built in ApplicationController for simplicity.
Explaination of notifyPropertyChange():
This is called because when we are inserting an new string into the selected array, using the push functionality of arrays.
I have used the push method because this is the most efficient way to add a new entry into an existing array.
While Ember does have a pushObject method that is supposed to take care of the notification as well, I couldn't get it to honour this. So this.notifyPropertyChange("selected"); tells Ember that we updated the array. However I'm hoping that's not a dealbreaker.
Alternative to Ember Component - Implemented as a View
If you don't wish to use it in Component format, you could implement it as a view. It ultimately achieves the same goal, but this may be a more familiar design pattern to you.
See this JSBin for implementation as a View. I won't include the full code here, because some of it is the same as above, you can see it in the JSBin
Usage:
Create an instance of App.SelectFilterBoxView, with a controller that has a data and selected property:
var myView = App.SelectFilterBoxView.create({
controller: Ember.Object.create({
data: DATA.model_data,
selected: ['Author','']
})
});
Then append the view as required, such as to #main.
myView.appendTo("#main");
Unfortunately your code doesn't run, even after adding Ember as a library in your JSFiddle, but ContainerView is probably what you're looking for: http://emberjs.com/api/classes/Ember.ContainerView.html as those views can be dynamically added/removed.
this.$().remove() or this.$().append() are probably what you're looking for:
Ember docs.

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 } );
}