Google Charts - No data available - Able to display a blank chart? - javascript

How can I still have Google Charts still show a line chart if my data array looks like this?
[['Date','Line']]
i.e. just the axis are defined. Most of my charts have data imported but some have nil on the data. I would like to display a blank chart. With data above I get an error message instead of a chart.
Here is code in my view
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(#{#visiting_spread_movement_array});
var options = {
title: 'Point Spread Movements for #{#event.visiting_team}'
};
var chart = new google.visualization.LineChart(document.getElementById('show-spread-visiting'));
chart.draw(data, options);
}

Well, to draw the chart you need at least one data point. To archieve this, you could use this workaround:
var data = google.visualization.arrayToDataTable([
[{
f: 'Date',
type: 'date' // wont work whithout this
}, {
f: 'Line',
type: 'number' // wont work whithout this
}], ]);
var options = {
title: 'Company Performance'
};
if (data.getNumberOfRows() == 0) { // if you have no data, add a data point and make the series transparent
data.addRow([new Date(), 0])
options.series = {
0: {
color: 'transparent'
}
}
}
Full fiddle: http://jsfiddle.net/qaLgh955/

Related

GoogleCharts - Data column(s) for axis #0 cannot be of type string

I'm building a web app using ExtJS, and I have a Google Chart that displays the number of days it takes for a task to be completed, along with the count for those days. The aim is to easily see if the tasks are being done within a reasonable amount of time, or if a lot of the task are completed at a much longer time period.
I can fetch the data with no problems, and I convert the raw data to something that Google Charts can process using a function:
var output_data= "";
var output_data_array = [];
var data_count = data.length;
google.charts.load('current', {'packages':['corechart', 'bar']});
var header = "[\"Days\", \"Count\", { role: \"style\" } ],";
output_data_array.push(["Days, type: 'string'", "Count, type: 'number'", "{role: \"style\"}"]);
for(var i = 0 ; i < data_count ; i++){
var data_entry = data[i];
var number_of_days = data_entry.days;
var count = parseFloat(data_entry.count);
var color;
if(number_of_days < limit){
color = 'green';
}
else{
color = 'red';
}
output_data_array.push([number_of_days, count, color]);
}
var output_data_table = google.visualization.arrayToDataTable([
output_data_array
], false);
return output_data_table;
The function above generates my data array, which includes a data header before the actual data. I call this function in this function below:
var graph_data = this.convertData_forGoogleCharts(analytics_data_array, 15);
google.charts.load('current', {'packages':['corechart', 'bar']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var view = new google.visualization.DataView(graph_data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
var options = {
title: "Test Chart",
width: width,
height: height,
bar: {groupWidth: "95%"},
legend: { position: "none" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("myChartPanel"));
chart.draw(view, options);
}
However, after I ran this, I got the following error:
Data column(s) for axis #0 cannot be of type string
Which is odd because I added in the a type field in the column header. I'm also not sure if I can do addColumn in my arrayToDataTable like how it would go for DataTable.
I think the problem is with the following statement...
var output_data_table = google.visualization.arrayToDataTable([
output_data_array
], false);
output_data_array is already defined as an array,
so no need to wrap in another array.
try as follows...
var output_data_table = google.visualization.arrayToDataTable(output_data_array, false);
UPDATE
the new error resulted from the column headings.
here, object notation should be used to define the type.
instead, strings are being passed in the following statement.
output_data_array.push(["Days, type: 'string'", "Count, type: 'number'", "{role: \"style\"}"]);
and since object notation is not used,
the method does not recognize the style role,
and tries to use a string value for series data,
which results in error.
using the data table constructor is fine,
but if you want to correct arrayToDataTable,
change to the following...
output_data_array.push(["Days", "Count", {role: "style", type: "string"}]);
or...
output_data_array.push([
{label: "Days", type: "string"},
{label: "Count", type: "number"},
{role: "style", type: "string"}
]);
I followed WhiteHat's answer above, but I got a new error:
All series on a given axis must be of the same data type.
Not sure if there's anything wrong with my data, I did a log of my array and I had:
The data looks uniform to me. I'm not sure how to go about this, so I tried a DataTable instead, as I saw a DataTable with a style header. I re-wrote my data converter function as such:
var data_table = new google.visualization.DataTable();
data_table.addColumn({type: 'string', label: 'Number of Days'});
data_table.addColumn({type: 'number', label: 'Count'});
data_table.addColumn({type: 'string', role: 'style'});
for(var i = 0 ; i < data_count ; i++){
var data_entry = data[i];
var number_of_days = data_entry.days;
var count = parseFloat(data_entry.count);
var color;
if(number_of_days < tat_limit){
color = 'green';
}
else{
color = 'red';
}
data_table.addRow([number_of_days, count, color]);
}
output_data = header + output_data;
return data_table;
And then in the main function, it's being used as:
function drawChart() {
var graph_data = this.convertData_forGoogleCharts(analytics_data_array, 15);
var view = new google.visualization.DataView(graph_data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
var options = {
title: "Test Chart",
width: width,
height: height,
bar: {groupWidth: "95%"},
legend: { position: "none" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("myChartPanel"));
chart.draw(view, options);
}
This one worked like a charm, but I'm still open to revisiting the arrayToDataTable solution.

Adding filters and charting the results in Google Visualization

I have a Water Usage Sample Google Spreadsheet with Month, Day, Time, Usage, and Gallons columns.
I'd like to build a dashboard with a Month filter, Day filter, Usage filter, Column Chart and Pie Chart. By default (with no filter selections made), I'd like the column chart to display a sum of gallons by month and the pie chart to display the total usage breakdown.
If a specific month is selected in the Month filter, I'd like the column chart to then display the sum of gallons for each day within that month and the pie chart to display the usage breakdown for that month. If a specific month and day is selected in the month filter and day filter, then I would like the column chart to then display each "gallons" entry by time for that month/day and the pie chart to display the usage breakdown for that month/day. If a specific usage is selected in the usage filter, I'd like the column chart to operate in the same manner as previously described, while only factoring the data for that specific usage. The pie chart would obviously just show 100% of that usage.
Here is the fiddle I've been working on.
google.load('visualization', '1.1', {
'packages': ['corechart']
});
google.setOnLoadCallback(drawStuff);
function drawStuff() {
var opts = {sendMethod: 'auto'};
// Replace the data source URL on next line with your data source URL.
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1oQTmYteohmVxiBReIyh_tRuOLIx6CXwgw0MuNw5jTTw/gviz/tq?sheet=Sheet1&headers=1&range=A1:E2000', opts);
// Send the query with a callback function.
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var columnData = google.visualization.data.group(data, [{
column: 1,
type: 'date'
}], [{
column: 4,
label: 'Gallons',
aggregation: google.visualization.data.sum,
type: 'number'
}]);
var pieData = google.visualization.data.group(data, [{
column: 3,
type: 'date'
}], [{
column: 4,
label: 'Gallons',
aggregation: google.visualization.data.sum,
type: 'number'
}]);
// Set chart options
var options = {
'title': 'WaterUsage',
'width': 400,
'height': 300
};
// Instantiate and draw our chart, passing in some options.
var columnChart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
columnChart.draw(columnData, options);
var pieChart = new google.visualization.PieChart(document.getElementById('chart_div2'));
pieChart.draw(pieData, options);
This was mainly derived from this thread. Any ideas?

Highcharts chart creation using d3.csv

This is in continued to my question here
I was having a lot of problems in creating highcharts basic charts using CSV data from my local filesystem without using a server/framework and just basic HTML/CSS/JS etc
So, finally, I got an idea to create a chart inside "d3.csv" function wherein we can add highchart functions insdie d3.csv ones
But, there seems to be something very silly wrong, I'm trying with a very basic code and table.
HTML code has only container div element,
Javascript
d3.csv("test.csv", function(data) {
data.forEach(function(d) {
name = d.name,
apples = +d.apples
});
console.log(data[2]);
dataset = data;
//display();
console.log(dataset[0]);
console.log(dataset[0].name);
function push(a)
{
var filter = [];
for (i=0; i<a.length ; i++)
{
filter.push(a[i].apples);
//console.log (filter);
}
return filter;
}
window.apples = push(dataset);
console.log(apples);
$(function () {
$('#container').highcharts({
chart: {
type : 'bar'
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: [dataset[0].name, dataset[1].name]
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [{
data: apples
}
]
});
})
});
test.csv :
name,apples
John,8
Jane,3
My console is showing "apples" correctly as [8,3]. I'm getting an empty graph on screen with only axes shown and nothing inside and also, x axis and y axis elements are interchanged.
What am I doing wrong here? Is the global variable - apples, not being accessed inside highcharts fucntions?
UPDATE :
Found the answer, but only one number is showing up.
I have 2 more questions :
How do I show the whole series?
Is this a good method to draw highcharts or will I face many issues later?
Found the solution to this, myself, for a change.
Highcharts will expect function to be parsed in their format ( Highcharts error 14 in console)
Changed my function above to this,
for (i=0; i<a.length ; i++)
{
x = a[i].apples;
y = parseFloat(x)
filter.push(y);
}
return filter;
}
window.apples = push(dataset);
And the series part to this :
series: [{
data : [apples]
}
]
This is finally, giving me a graph with one bar (John, 8) now!!
The second number is still not being loaded, if someone wants to help with that, please comment below.
Update :
changed
data : [apples] -> data: apples (Correct format)
Credits : PawelFus

How to use Google Chart with data from a csv

I have a csv file that looks like that:
week,value1,value2
1,2,3
2,7,9
I would like to plot a stacked graph of it using google chart (week being my x (horizontal) values and values1 and values2 being the two set of y's). Unfortunately, I didn't find any easy way to do so. That probably relates to me being a complete noob in js.
Is there any simple way to do that?
The jquery-csv library provides the ability to translate a string of csv into an array to be used by google.visualization.arrayToDataTable() (their example here). To make this work, add jquery.csv.js to your server (in the example below I assume it is in the same folder as your HTML) and link to it in your <head>. The following is a simple script you can add to your <head> to get started. I assume a scatter chart, but this process works for any of the charts here. You will also need a <div> with id="chart" for this to work.
// load the visualization library from Google and set a listener
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
// this has to be a global function
function drawChart() {
// grab the CSV
$.get("example.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);
// 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'
};
// create the chart object and draw it
var chart = new google.visualization.ScatterChart(document.getElementById('chart'));
chart.draw(view, options);
});
}
I have been searching for a while, and found the solution on a Google group discussion.
https://groups.google.com/forum/#!topic/google-visualization-api/cnXYDr411tQ
I have tried it, and it works!
In this case, we have to specify the header types of our csv file.
var queryOptions = {
csvColumns: ['number', 'number', 'number' /* Or whatever the columns in the CSV file are */],
csvHasHeader: true /* This should be false if your CSV file doesn't have a header */
}
/* csvUrl is the path to your csv */
var query = new google.visualization.Query(csvUrl, queryOptions);
query.send(handleQueryResponse);
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var chart = new google.visualization.ColumnChart(document.getElementById('your div'));
// Draw your chart with the data table here.
// chart.draw(view, queryOptions);
}
What server side scripting language are you working in (php, asp)?
One option could be to import the data from a spreadsheet saved in Google Drive, see here for a PHP based example of saving and extracting data from Google Docs. This would then enable you to update the spreadsheet and the chart would automatically plot the new data.

draw simple line chart with google chart json data with dates on x axis

I have taken a look at the other answers at SO, but none caters to my need.
Here is the documentation which tells how to plot dates on charts. Following is one of the sample json objects:
datetime: "2012-07-07"
hours: "0.6"
shop: "WalMart"
name: "Andrew"
__proto__: Object
I use the following code to add rows and columns:
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Hours');
$.each(hour_logs, function(key, value){// hour_logs is the collection of json objects, the sample is shown above.
ymd = value.datetime.split("-");
var dt = new Date(parseInt(ymd[0]), parseInt(ymd[1]), parseInt(ymd[2]));
data.addRow(dt, parseInt(value.hours));
});
console.log(data);
var options = {
title: 'Daily Logs',
displayAnnotations: true,
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
But i get an error, uncaught Error: Not an array. How to fix it.
You are not providing an array when adding a row.
Should be:
data.addRow([dt, parseInt(value.hours)]);
instead of:
data.addRow(dt, parseInt(value.hours));

Categories