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

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

Related

How to give api count and date value to google line chart?

I am making a simple web counter using count api. I am good in getting the counts. Now, I'm making a google line chart to show count value with the date in graph form. So, please help me how to set the date and count data in drawChart() function to get the count as per the date. And the graph should have 5 days of count. How to achieve this solution. Sincere Thanks in Advance!
const counter = document.getElementById('count');
updateVisitCount();
function updateVisitCount() {
fetch('https://api.countapi.xyz/update/demo/sample/?amount=1').then(res => res.json())
.then(res => {
counter.innerHTML = res.value;
});
}
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'Number of Site Visits'],
]);
var options = {
title: 'Site Visits',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
That's working.
var counters=[
['string', 'value'],
];
setInterval(()=>{
fetch('https://api.countapi.xyz/update/demo/sample/?amount=1').then(res => res.json())
.then(res => {
var dt = new Date();
var secs = dt.getSeconds()
counters.push(
[secs,res.value]
)
if(counters.length>3){
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
}
});
},1000);
function drawChart() {
var data = new google.visualization.arrayToDataTable(counters);
var options = {
title: 'Site Visits',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}

Google Visualization ColorFormat Exact Match String

Is it possible to colour a text column based off an exact match? I have tried setting the from and to, to the same value but it doesn't colour the cell?
formatter.addRange('danger', 'danger', 'red', 'white');
Thanks
The high boundary, or To value, is non-inclusive
so it has to be something after 'danger'
including a space at the end will color the cell
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'string');
data.addColumn('number', 'number');
data.addRow(['danger', 0]);
data.addRow(['safe', 1000]);
data.addRow(['unknown', 1001]);
var formatColor = new google.visualization.ColorFormat();
formatColor.addRange('danger', 'danger ', 'white', 'red');
formatColor.addRange(1000, 1001, 'white', 'green');
formatColor.format(data, 0);
formatColor.format(data, 1);
var chart = new google.visualization.Table(document.getElementById('chart_div'));
chart.draw(data, {
allowHtml: true
});
},
packages: ['table']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google Charts - Table has no columns when it has columns

I'm attempting to create a Google Charts Line Chart. The Json I'm returning from a C# MVC controller method looks as follows:
My JS code looks as follows:
function drawChart() {
var jsonData = $.ajax({
url: "/Misc/GetWeeklySalesData/",
dataType: "json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
alert(data);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chartDiv'));
chart.draw(data, { width: 400, height: 240 });
I'm getting the message 'Table has no columns' when clearly it does.
To create the data table directly from JSON, it must be in a specific format:
Format of the Constructor's JavaScript Literal data Parameter
Otherwise, you can create a blank data table and load the rows manually:
$.ajax({
url: "/Misc/GetWeeklySalesData/",
dataType: "json",
}).done(function (jsonData) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Week');
data.addColumn('number', 'Retail');
data.addColumn('number', 'Wholesale');
jsonData.forEach(function (row) {
data.addRow([
row.Week,
row.Retail,
row.Wholesale
]);
});
var chart = new google.visualization.LineChart(document.getElementById('chartDiv'));
chart.draw(data, {
width: 400,
height: 240
});
}).fail(function (jq, text, err) {
console.log(text + ' - ' + err);
});
Note: highly recommend not using --> async: false. Use the done callback instead...

Change color of a bar in google columnchart

I am using columnchart to generate a chart . Below is the code:
function drawActiveJobsChart() {
var i=0;
var j=0;
var data = new google.visualization.DataTable();
data.addColumn('string','Systems');
data.addColumn('number', 'Counts');
$.getJSON('SubSystemNumbers.action', function(json) {
$.each( json.SysActNum, function( key, val ) {
i++;
});
data.addRows(i);
$.each( json.SysActNum, function( key, val ) {
if (val>=30) {
data.setProperty(j,1,'style','color:red');
}
data.setValue(j, 0,key);
data.setValue(j, 1,val);
j++;
});
});
var options = {
title: 'System Numbers',
width:900, height:400,
allowHtml: true,
hAxis: {title: 'Systems', titleTextStyle: {color: 'red'},textStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById(chartDiv));
chart.draw(data, options);
}
Now i have added logic to change the bar color to red when return val is greater than 30 . I tried running in debug and code is executing fine but bar is not showing in red . Please suggest ! Help is appreciated
Setting the "style" property of a cell is not going to change the color of a bar, you need to add a "style" role column to your DataTable:
var data = new google.visualization.DataTable();
data.addColumn('string','Systems');
data.addColumn('number', 'Counts');
data.addColumn({type: 'string', role: 'style'});
and add the style information to this column:
$.getJSON('SubSystemNumbers.action', function(json) {
$.each( json.SysActNum, function( key, val ) {
var style = (val >= 30) ? 'color: red' : null;
data.addRow([key, val, style]);
});
});
see working example based on your code here: http://jsfiddle.net/asgallant/dGYs7/
Just in case somebody else runs in to the same issue as me:
I had a similar problem where I couldn't change the color of specific bars in a bar-chart. I did as the documentation said, and tried the answer here by asgallant, but nothing worked.
Turned out, I just needed to change google.charts.Bar to google.visualization.ColumnChart.

Google Charts multiple gauges

I'm using Google Charts and I'm trying to add multiple charts to one json call.
The chart style is gauge.
The example below works for only one gauge "CPU" I'm not that great with the charts but I did create a working example that updates.
What I want to add is two more gauges and the json array names would be ram,bandwidth.
So the json would look something like this {"cpu":0,"ram":0,"bw":0}
How would I go about adding two more gauges?
<div id='chart_div'></div>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js'></script>
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>
var chart;
var charts;
var data;
google.load('visualization', '1', {packages:['gauge']});
google.setOnLoadCallback(initChart);
function displayData(point) {
data.setValue(0, 0, 'CPU');
data.setValue(0, 1, point);
chart.draw(data, options);
}
function loadData() {
// variable for the data point
var c;
$.getJSON('http://example.com/json.php', function(data) {
// get the data point
c = data.cpu;
displayData(c);
});
}
function initChart() {
data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', 'Value');
data.addRows(1);
chart = new google.visualization.Gauge(document.getElementById('chart_div'));
options = {width: 120, height: 120, greenFrom: 0, greenTo: 50, redFrom: 75, redTo: 100,
yellowFrom:50, yellowTo: 75, minorTicks: 5};
loadData();
setInterval('loadData()', 1000);
}
</script>
If your data is in the form {"cpu":0,"ram":0,"bw":0}, then you can add it to the DataTable for the Gauges like this:
function initChart() {
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
var options = {
width: 120,
height: 120,
greenFrom: 0,
greenTo: 50,
redFrom: 75,
redTo: 100,
yellowFrom:50,
yellowTo: 75,
minorTicks: 5
};
function drawGauge () {
$.getJSON('http://example.com/json.php', function(json) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', 'Value');
for (x in json) {
data.addRow([x, json[x]]);
}
chart.draw(data, options);
});
}
setInterval(drawGauge, 1000);
}
google.load('visualization', '1', {packages:['gauge'], callback: initChart});