Adding legend to Google chart - google-visualization

I am trying to add the column headings to the legend in this line graph, they should be the first row within the data table. The graph works fine if I remove the headings, however when I try load it with the headings I am getting nothing. Below is the output of the code that creates the input table it looks correct based on the google api example. Thanks
['Date','Species A', 'Species B'],['2013-08-27',3,1], ['2013-09-17',4,1], ['2013-08-23',1,1], ['2013-08-10',2,8]
The relevant bits of code
$result = mysqli_query($con,"SELECT * FROM Species");
while($row1 = mysqli_fetch_array($result))
{
$data1[]= "['" . $row1['Date'] . "'," . $row1['SpeciesA'] . "," . $row1['SpeciesB'] . "]";
}
$headings = "['Date','Species A', 'Species B'],";
$headingdata = $headings . implode(",\n",$data1);
echo $headingdata;
?>
<html>
<head>
<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()
{
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Species A');
data.addColumn('number', 'Species B');
data.addRows([
<?php echo $headingdata;?>
]);

If you are creating the DataTable like that, you don't want to include the $headings data in the data you are passing to the DataTable's #addRows method. Those should only be included if you are using the arrayToDataTable constructor.
Most of the charts will include the column labels as the series labels in the legend by default.
If you use the solution I posted in your other question, you shouldn't have any problems with this.

Related

Google Charts Table displaying incorrect date

In this example google charts table is given a date of 1/1/16 and displays 12/31/15. Do I need to use some kind of timezone or something?
<div id="chart"></div>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:['corechart', 'table']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'dt');
data.addRows([[new Date("2016-01-01")]]);
var view = new google.visualization.DataView(data);
var table = new google.visualization.Table(document.getElementById('chart'));
table.draw(data);
}
</script>
not related to google-visualization, the real answer is here...
Why does Date.parse give incorrect results?
use format such as '01/01/2016' to get expected results...

How to control haxis dataformat in google visualization chart?

I'm using the Google visualization chart in my application for drawing a line chart. It works great except one thing in the hAxis the entered number converts itself to thousands like below. I know this is happening because im trying to display huge numbers but still i would like to know if there is way to get around this?
Code
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['line']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Degree Level');
data.addColumn('number', 'Graduate or professional degree');
data.addColumn('number', "Bachelor's degree");
data.addColumn('number', "Associate's degree");
data.addColumn('number', "High school or vocational training");
data.addRows([
[2, 39758,93179, 78578,49141],
[3, 100747, 300646, 220982,100456],
[4, 49964, 68022, 21092,6943],
[5, 150370, 124868, 27120,8204]
]);
var options = {
chart: {
title: 'Education Report',
subtitle: 'distributed by experience'
},
width: 900,
height: 500
};
var chart = new google.charts.Line(document.getElementById('linechart_material'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="linechart_material"></div>
</body>
</html>
Output
Can someone let me know how can i make the hAxis to display in number?
There are two solutions to get the format that you want.
Either you use version 1 of the corecharts package :
so load the package like this :
// instead of : google.load('visualization', '1.1', {packages: ['line']});
google.load('visualization', '1', { packages: ['corechart'] });
and call your chart like this :
// instead of : var chart = new google.charts.Line(document.getElementById('linechart_material'));
var chart = new google.visualization.LineChart(document.getElementById('linechart_material'));
And you'll get what you want.
See a demo jsfiddle here.
Or alternatively,
Use version 1.1 of the package (you already do in your example) like this :
google.load('visualization', '1.1', {packages: ['line']});
and then specify in your chart options the vAxis format like this :
vAxis: { format: '###,###,###' },
and load the chart this way, so that the vAxis settings are taken into account :
chart.draw(data, google.charts.Line.convertOptions(options));
That'll work too.
See a demo jsfiddle here.
The problem here is that the way options are defined has changed from v.1 to v.1.1. So if you want to use the v.1.1 package you have to call google.charts.Line.convertOptions() for your options to be interpreted correctly.

Google Chart not showing info from google sheet unless sheet is accessed

I have a bunch of sheets that I'm using to store the marks of my students for a couple of my classes. On my website, I am using HTML and Google's Query Language to pull info from the sheets (2 columns...the students numbers of each student and their mark). If I've edited the spreadsheet on any given day, the chart shows up properly, but if I have not edited it that day then it shows incorrect values for their marks or old values for their marks. I think it's something to do with the sheets, but I can't be sure.
Here's the HTML code from my site:
<html>
<head>
<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 query = new google.visualization.Query(
'https://docs.google.com/spreadsheet/ccc?key=14mPTcYYraMyuBnEFSJW74ZQ3xjWSSOuDqoxB2VrvAvw&tq=select%20D%2C%20E%20where%20D%3C%3E%22Avatar%22%20order%20by%20E%20desc%20label%20E%20%22Experience%20Points%22');
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('columnchart'));
var options = {'title':'Experience Points',
'width':'927',
'height':'510',
'chartArea': {'left':'50', 'width':'90%'},
legend: { position: 'top', maxLines: 2 },
hAxis: {showTextEvery: 1, slantedText: true, slantedTextAngle: 90, viewWindow:{max:33}},
bar:{groupWidth: '60%'},
isStacked: true};
chart.draw(data, options);
}
</script>
<title>Data from a Spreadsheet</title>
</head>
<body>
<span id='columnchart'></span>
</body>
</html>
Any ideas? By the way, the sheet is set so that anyone on the internet can find and view.

Google geochart doesn't show continents

I'm using google geochart to display data.
My code:
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>
google.load('visualization', '1', { 'packages': ['geochart'] });
google.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var geochart = new google.visualization.GeoChart(
document.getElementById('visualization'));
var options = {region: 'world', resolution: 'continents', width: 556, height: 347};
var data = google.visualization.arrayToDataTable([
['continents', 'Aircrafts'],
['Asia', 700]
]);
geochart.draw(data, options);
};
</script>
<div id="visualization" style="width: 800px; height: 400px;"></div>
In chart it doesn't show asia as data.
Although the 'continents' resolution option isn't in the official docs it does work. You need to change your data table to include a column of continent region codes, e.g.:
var data = google.visualization.arrayToDataTable([
['Region code', 'Continent', 'Aircraft'],
['142', 'Asia', 700]
]);
geochart.draw(data, options);
The region codes are required but don't get rendered in the tooltips. The codes matching each continent are explained here, beneath the options in the section called 'Continent Hierarchy and Codes'. It doesn't actually say you need to use them in your data table (that would be too easy...)
The only caveat is that I haven't yet found a way to get it to recognise the subregion codes that will allow separating 'Americas' into North & South. If you stick to using the continent codes then they should work - they do for me. Note that the codes need to be in the data table as strings.
See here for a working example : http://jsfiddle.net/6hrhj9qs/
You are using undocumented options described in this post
There it was also said that this bug would be fixed soon... and date was 5/25/11!
I didn't find other update.
Try using VectorWorkz' GeoChart, it supports Asia as a Continent and you have full control of the regions and add/modify the underlying maps to your needs. We can help create custom maps for you too.

google visualization + jboss seam 2

I'm trying to use google visualization api in jboss seam 2 project.
I have created a simple example which is actually taken from Google Quick Start page.
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
When I open it as file in web browser it works nicely. But when I put it to my Jboss Seam 2 project and open in web browser, it generates an error message "b[c] is undefined" on red background.
And here what I see when I open page source in browser:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="/MCMS/a4j/g/3_3_3.Final/org/ajax4jsf/framework.pack.js" type="text/javascript"></script>
<script src="/MCMS/a4j/g/3_3_3.Final/org/richfaces/ui.pack.js" type="text/javascript"></script>
<link class="component" href="/MCMS/a4j/s/3_3_3.Final/org/richfaces/skin.xcss/DATB/eAGTKJ8eErp8hjQADcsDKg__" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
As you can see Jboss Seam adds some other script srcs for a4j.
Is it possible that a4j javascript conflicts with google visualization api javascript?
Is there any idea how to resolve this?
Finally found the solution here
Google charts error:Cannot read property 'length' of undefined; Debugging error in Google Charts
and here
http://code.google.com/p/google-visualization-api-issues/issues/detail?id=501 .
Adding the following hack in the beginning of the script:
Array.prototype.reduce = undefined;
or more gracefully:
Array.prototype.reduce=function(fun){var len=this.length>>>0;if(typeof fun!="function")throw new TypeError;if(len==0&&arguments.length==1)throw new TypeError;var i=0;if(arguments.length>=2)var rv=arguments[1];else{do{if(i in this){var rv=this[i++];break}if(++i>=len)throw new TypeError;}while(true)}for(;i<len;i++)if(i in this)rv=fun.call(undefined,rv,this[i],i,this);return rv};
solves the problem!