I have a query that get from SQL a list of names and theirs fields (OnTime & Delayed). If i use an echo $datosGrafico in php, it shows the below:
['Agustin', 17, 1 ],
['Andrea', 79, 0 ],
['Carla', 17, 0 ],
['Cecilia', 6, 0 ],
['Denise', 0, 0 ],
['Diego', 3, 0 ],
['Ezequiel', 0, 0 ],
['German', 0, 0 ],
That part is fine. the problem appear once i try to put that variable in the google chart javascript. The script just stop working:
<html>
<head>
<script type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["bar"]});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = google.visualization.arrayToDataTable([
['Analista', 'On Time', 'Delayed'],
//(The variable $datosGrafico SHOULD GO HERE and avoid to insert every name mannualy)
['Agustin', 17, 1],
['Lucas', 6, 2],
]);
var options = {
width: 425,
height: 450,
chart: {
title: 'Spread of SLAs by Analist',
subtitle: 'Amount of Tickets'
},
bars: 'horizontal' // Required for Material Bar Charts.
}
;
var chart = new
google.charts.Bar(document.getElementById('dual_x_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="dual_x_div" style="width: 300px; height: 450px;"></div>
</body>
Any idea why this is happening?
I hope I understood you correctly. This works:
google.charts.load("current", {packages:["bar"]});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff()
{
var data = google.visualization.arrayToDataTable(
[
['Analista', 'On Time', 'Delayed'],
['Agustin', 17, 1 ],
['Andrea', 79, 0 ],
['Carla', 17, 0 ],
['Cecilia', 6, 0 ],
['Denise', 0, 0 ],
['Diego', 3, 0 ],
['Ezequiel', 0, 0 ],
['German', 0, 0 ]
]);
var options =
{
width: 425,
height: 450,
chart:
{
title: 'Spread of SLAs by Analist',
subtitle: 'Amount of Tickets'
},
bars: 'horizontal' // Required for Material Bar Charts.
}
;
var chart = new
google.charts.Bar(document.getElementById('dual_x_div'));
chart.draw(data, options);
}
<script type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"></script>
<div id="dual_x_div" style="width: 300px; height: 450px;"></div>
I've found the solution based on comments here! Thanks!
The php PDO query, return the variable:
$datosGrafico
I added some lines to save that variable result in a php file
$fichero = 'tpl\include\test.php';
$actual = $datosGrafico;
file_put_contents($fichero, $actual);
and then, i've just added the php code to read that file:
dataTable = new google.visualization.DataTable();
var newData = <?php include ('tpl\include\test.php')?>
var numRows = newData.length;
var numCols = newData[0].length;
// in this case the first column is of type 'string'.
dataTable.addColumn('string', newData[0][0]);
// all other columns are of type 'number'.
for (var i = 1; i < numCols; i++)
dataTable.addColumn('number', newData[0][i]);
// now add the rows.
for (var i = 1; i < numRows; i++)
dataTable.addRow(newData[i]);
Hope this help you in the future!
Related
I am trying to sum the minutes of two bars on a bar chart and it breaks. jsfiddle
I'm basing myself on the example from the Stacked column charts, but I can't get it to work with "H: i: s"
this is my code
var GoogleColumnBasic = function() {
var _googleColumnBasic = function() {
google.charts.load('visualization', '1.0', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var dtos= [];
var data = google.visualization.arrayToDataTable([
['','preparation time ', 'time when he retired',
{ role: 'annotation' } ],
['box 1', '00:43:22', '00:03:22', ''],
['box 2', '00:13:22', '00:73:22' , ''],
['box 3', '00:23:22', '00:53:22', '']
]);
var options = {
height: 350,
isStacked: true
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
//chart.draw(data, options);
chart.draw(data, google.charts.Bar.convertOptions(options));
}
}
return {
init: function() {
_googleColumnBasic();
}
}
}();
GoogleColumnBasic.init();
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>
thanks.
you can use a 'timeofday' column, see working with timeofday.
The DataTable timeofday column data type takes an array of either 3 or 4 numbers, representing hours, minutes, seconds, and optionally milliseconds, respectively. Using timeofday is different than using date and datetime in that the values are not specific to a date, whereas date and datetime always specify a date. For example, the time 8:30am would be: [8, 30, 0, 0], with the 4th value being optional ([8, 30, 0] would output the same timeofday value).
the data table used to draw the chart would be similar to the following...
var data = google.visualization.arrayToDataTable([
['', 'time of ', 'retirar', {role: 'annotation', type: 'string'}],
['Caja 1', [0, 43, 22], [0, 3, 22], ''],
['Caja 2', [0, 13, 22], [0, 73, 22], ''],
['caja 3', [0, 23, 22], [0, 53, 22], '']
]);
see following working snippet...
var GoogleColumnBasic = function() {
var _googleColumnBasic = function() {
google.charts.load('current', {
packages: ['corechart']
}).then(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['', 'time of ', 'retirar', {role: 'annotation', type: 'string'}],
['Caja 1', [0, 43, 22], [0, 3, 22], ''],
['Caja 2', [0, 13, 22], [0, 73, 22], ''],
['caja 3', [0, 23, 22], [0, 53, 22], '']
]);
var options = {
height: 350,
isStacked: true,
colors: ['#4285f4', '#a1c2fa'],
theme: 'material',
chartArea: {
left: 64,
top: 48,
right: 32,
bottom: 64,
height: '100%',
width: '100%'
},
height: '100%',
legend: {
position: 'top'
},
width: '100%'
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, (options));
}
}
return {
init: _googleColumnBasic
}
}();
GoogleColumnBasic.init();
html, body {
height: 100%;
margin: 0px 0px 0px 0px;
padding: 0px 0px 0px 0px;
}
#chart_div {
height: 100%;
min-height: 400px;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
NOTES
the jsapi loader has been deprecated and should no longer be used.
instead, use the new loader.js
<script src="https://www.gstatic.com/charts/loader.js"></script>
this will only change the load statement, see above snippet.
do not recommend using a material chart. (google.charts.Bar)
they do not work well with 'timeofday' columns,
they do not support column roles such as 'annotation',
AND many of the chart options simply do not work, see Tracking Issue for Material Chart Feature Parity
instead, we can use option --> theme: 'material' on a classic chart (google.visualization.ColumnChart)
I have been playing around with Google charts quite a bit over in the google charts play ground here
This is the code that shows the image below
<script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js">
</script>
<script type = "text/javascript">
google.charts.load('current', {packages: ['corechart']});
</script>
<div id = "container" style = "width: 550px; height: 400px; margin: 0 auto">
</div>
<script language = "JavaScript">
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Genre', 'Fantasy & Sci Fi', 'Romance', 'Mystery/Crime', 'General',
'Western', 'Literature', { role: 'annotation' } ],
['2010', 10, 24, 20, 32, 18, 5, ''],
['2020', 16, 22, 23, 30, 16, 9, ''],
['2030', 28, 19, 29, 30, 12, 13, '']
]);
var options = {
title: "h",
width: 600,
legend: { position: "none" },
isStacked:true
};
var chart = new google.visualization.BarChart(document.getElementById('container'));
chart.draw(data, options);
}
google.charts.setOnLoadCallback(drawChart);
</script>
Chart Image
How can add a link clickable to each data?
Solution
Handling Click and link Redirection
<script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js">
</script>
<script type = "text/javascript">
google.charts.load('current', {packages: ['corechart']});
</script>
<div id = "container" style = "width: 550px; height: 400px; margin: 0 auto">
</div>
<script language = "JavaScript">
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Genre', 'Fantasy & Sci Fi', 'Romance', 'Mystery/Crime', 'General',
'Western', 'Literature', { role: 'annotation' } ],
['2010', 10, 24, 20, 32, 18, 5, ''],
['2020', 16, 22, 23, 30, 16, 9, ''],
['2030', 28, 19, 29, 30, 12, 13, '']
]);
var options = {
title: "h",
width: 600,
legend: { position: "none" },
isStacked:true
};
var chart = new google.visualization.BarChart(document.getElementById('container'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler(e) {
var selection = chart.getSelection();
if (selection.length == true && selection[0].row != null) {
console.log(selection[0])
//alert('You selected ' +data.getValue(selection[0].row, selection[0].column));
//window.open(data.getValue(selection[0].row, 0));
window.open('https://www.google.com/search?q='+data.getColumnLabel(selection[0].column)+':'+data.getValue(selection[0].row, selection[0].column));
}
}
}
google.charts.setOnLoadCallback(drawChart);
</script>
Below URL will help you to add link or click event on chart.
https://developers.google.com/chart/interactive/docs/events?csw=1
I have a huge problem with charts. Im trying to show just a few json value in the google chart, but I always get errors.
From the JSON body I only need the 'purchases all' and the 'Date' from the last month for the Chart. All the examples I have seen, they already got a static self defined Jsonbody. I hope you can help me and tell me what im doing wrong :(.
This is my jsFile, with the API response:
request(requestApi, function (error, response, body) {
if (error) {
return res.reject(error);
}
var dataJson = JSON.parse(body);
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(dataJson);
data.addRows([
[{v: dataJson[0].total_purchases.purchases_all,
f: dataJson[0].total_purchases.date }]
]);
var options = {
chart: {
title: 'chart '
},
hAxis: {
title: 'week'
},
vAxis: {
title: 'counts',
viewWindowMode: 'explicit',
viewWindow: {
max: 300,
min: 0
}
},
bars: 'vertical',
width: 600,
height: 500
};
var chart = new google.charts.Bar(document.getElementById('the_chart'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
The response from the API is this:
{
"total_purchases": [
{
"number": 0,
"purchases_website": 11,
"purchases_app": 10,
"purchases_all": 21,
"date": "2016-07-01"
},
{
"number": 3,
"purchases_website": 19,
"purchases_app": 32,
"purchases_all": 51,
"date": "2016-05-01"
},
{
"number": 1,
"purchases_website": 31,
"purchases_app": 34,
"purchases_all": 65,
"date": "2016-06-01"
},
{
"id": 2,
"purchases_website": 20,
"purchases_app": 12,
"purchases": 32,
"date": "2016-08-01"
}
]
}
When I console log the JSON.parse(body) I get this:
imageHERE
since the json is not in the format google expects,
load the data table manually
create blank data table
add columns
add rows with data from json
see following working snippet...
google.charts.load('current', {
callback: function () {
var dataJson = {"total_purchases": [
{
"number": 0,
"purchases_website": 11,
"purchases_app": 10,
"purchases_all": 21,
"date": "2016-07-01"
},
{
"number": 3,
"purchases_website": 19,
"purchases_app": 32,
"purchases_all": 51,
"date": "2016-05-01"
},
{
"number": 1,
"purchases_website": 31,
"purchases_app": 34,
"purchases_all": 65,
"date": "2016-06-01"
}
]};
// create blank data table
var data = new google.visualization.DataTable();
// add columns: Type Label
data.addColumn('string', 'date');
data.addColumn('number', 'website');
data.addColumn('number', 'app');
data.addColumn('number', 'all');
// add each row from json
dataJson.total_purchases.forEach(function (row) {
data.addRow([
row.date,
row.purchases_website,
row.purchases_app,
row.purchases_all
]);
});
// sort data table
data.sort([{column: 0}]);
var options = {
chart: {
title: 'chart '
},
hAxis: {
title: 'week'
},
vAxis: {
title: 'counts',
viewWindowMode: 'explicit',
viewWindow: {
max: 300,
min: 0
}
},
bars: 'vertical',
width: 600,
height: 500
};
var chart = new google.charts.Bar(document.getElementById('the_chart'));
chart.draw(data, google.charts.Bar.convertOptions(options));
},
packages: ['bar']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="the_chart"></div>
notes:
the above uses a discrete axis (first column is type: 'string')
in order to use a continuous axis (type: 'datetime'),
you may want to change the format of the json "date" value,
from --> "2016-06-01"
to --> "06/01/2016"
when loaded in the data table,
the current format will be offset by the timezone and could show an incorrect date,
it may also cause the data points to not align correctly with gridlines
and if using type: 'datetime', first column will change to...
data.addColumn('datetime', 'date');
and the add row statement would be...
data.addRow([
new Date(row.date),
row.purchases_website,
row.purchases_app,
row.purchases_all
]);
recommend using core chart instead, there are several config options that don't work with material charts
Tracking Issue for Material Chart Feature Parity #2143
core --> google.visualization.ColumnChart -- using --> packages: ['corechart']
material --> google.charts.Bar -- using --> packages: ['bar']
there is an option to get core chart close to look & feel of material
theme: 'material'
I'm currently working on a chart using google chart api, but i struggle at making a twice positive horizontal scale.
Like : 50 25 0 25 50 with a stacked chart bar centered on the '0' in the scale.
I kind of got it centered using a "dummy" invisible bar to push everything, but i can't find a way to get the horizontal axis label customized without editing the windowsview.
here's my actual code :
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawAnnotations);
function findMax(arr) {
var max = 0;
for (var n in arr) {
if (n > 0) {
var cMax = arr[n][2];
if (cMax > max)
max = cMax
}
}
return (max);
}
function findLine(arr) {
var max = 0;
for (var n in arr) {
if (n > 0) {
var cMax = arr[n][2] + arr[n][3] + arr[n][4];
if (cMax > max)
max = cMax
}
}
return (max / 2);
}
function space(arr, maxL) {
var max = findMax(arr);
for (var n in arr) {
if (n > 0) {
arr[n][1] = max - arr[n][2] + (maxL);
}
}
}
function drawAnnotations() {
var raw_data = [];
raw_data.push( ['Compétence', 'invisible', 'Expert', 'Certifié', 'Non certifié'] );
raw_data.push( ['Java', 0, 24, 31, 12] );
raw_data.push( ['PHP', 0, 17, 22, 10] );
raw_data.push( ['JavaScript', 0, 6, 10, 22] );
raw_data.push( ['Cpp', 0, 0, 0, 50] );
raw_data.push( ['C#', 0, 5, 10, 15] );
var maxL = findLine(raw_data);
space(raw_data, maxL);
var data = google.visualization.arrayToDataTable(raw_data);
var options = {
isStacked: true,
enableInteractivity: false,
width: 600, height: 400,
legend : 'none',
bar: { groupWidth: '85%' },
colors: ['ffffff','gray', 'yellow', 'red'],
hAxis: {
title: '',
baselineColor: '#fff',
gridlineColor: '#fff'
},
vAxis: {
title: '',
baselineColor: '#fff',
gridlineColor: '#fff'
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
JSfiddle Link
Currently i got what i want exept for the horizontal scale which is not set as i wish it to be.
(I tried to use multiple axes but it has proven to be unseccessfull).
edit: I add a link to an image of what kind of chart (scale) i'm looking to do.
UPDATE
I kinda got it working now :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawAnnotations);
function drawAnnotations() {
var raw_data = [];
raw_data.push( ['Compétence', 'Expert', 'Certifié', 'Non certifié'] );
raw_data.push( ['Java', -24, 45, 12] );
raw_data.push( ['PHP', -17, 22, 10] );
raw_data.push( ['JavaScript', -6, 10, 22] );
raw_data.push( ['Cpp', -0, 0, 50] );
raw_data.push( ['C#', -5, 10, 15] );
var data = google.visualization.arrayToDataTable(raw_data);
var options = {
isStacked: true,
width: $(window).width() * 0.8, height: 400,
legend : 'none',
bar: { groupWidth: '85%' },
colors: ['gray', 'yellow', 'red'],
interpolateNulls: true,
hAxis: {
title: 'Number',
gridlines: {
color: 'transparent'
}
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
$(window).load(function() {
$('text').each(function(i, el) {
if ($(this).text()[0] == '-')
$(this).text($(this).text().substr(1));
});
});
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
I had to change the google lib i was using :
previously was :
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
and now i'm using :
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
I'm not sure why it change something but without this change $(window).load was unable to reach "text" and i wasn't able to edit it.
Now i'm just converting a part of my chart to negative (the one i wanted on the left) and change the "negative" values from the scale using jquery.
There's just one thing left , the tooltip still show the negative value when you point on the "gray" area of the chart.
I still hope it may help someone else who struggle with this particular problem.
In fact, instead of modifying axis text via jQuery you could customize it via ticks feature as shown below:
hAxis: {
ticks: [{ v: -25, f: '25' }, 0, 25, 50, 75]
}
Regrading customizing tooltip label, you could consider the following solution to display non-negative value:
1) Attach onmouseover event to Google Chart:
google.visualization.events.addListener(chart, 'onmouseover', function (e) {
setTooltipContent(data, e);
});
2) Override tooltip negative value:
function setTooltipContent(data, e) {
if (e.row != null && e.column == 1) {
var val = Math.abs(data.getValue(e.row, 1));
var tooltipTextLabel = $(".google-visualization-tooltip-item-list li:eq(1) span:eq(1)");
tooltipTextLabel.text(val.toString());
}
}
Complete example
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawAnnotations);
function drawAnnotations() {
var raw_data = [];
raw_data.push(['Compétence', 'Expert', 'Certifié', 'Non certifié']);
raw_data.push(['Java', -24, 45, 12]);
raw_data.push(['PHP', -17, 22, 10]);
raw_data.push(['JavaScript', -6, 10, 22]);
raw_data.push(['Cpp', -0, 0, 50]);
raw_data.push(['C#', -5, 10, 15]);
var data = google.visualization.arrayToDataTable(raw_data);
var options = {
isStacked: true,
width: $(window).width() * 0.8, height: 400,
legend: 'none',
bar: { groupWidth: '85%' },
colors: ['gray', 'yellow', 'red'],
interpolateNulls: true,
tooltip: {isHtml: true},
hAxis: {
title: 'Number',
gridlines: {
color: 'transparent'
},
ticks: [{ v: -25, f: '25' }, 0, 25, 50, 75]
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'onmouseover', function (e) {
setTooltipContent(data, e);
});
}
function setTooltipContent(data, e) {
if (e.row != null && e.column == 1) {
var val = Math.abs(data.getValue(e.row, 1));
var tooltipTextLabel = $(".google-visualization-tooltip-item-list li:eq(1) span:eq(1)");
tooltipTextLabel.text(val.toString());
}
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
JSFiddle
I am trying to implement google charts in my project.
Where I want to display marks of last x tests on bar graph.
But the issue is, user can take any number of subjects for the test like only Math and History.So I only want to show that subjects in a bar chart.
I can not display 0 since "0" might infer that user got 0 marks in that subject. I just want to include those subjects which the user gives test for.
Is this possible in google Chart or any other library ?
Here is the code:
<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 data = google.visualization.arrayToDataTable([
['Math', 'Science', 'History', 'Geography', { role: 'annotation' } ],
['#1', 10, 24, 20, ''],
['#2', 16, 22, 23, ''],
['#3', 28, 19, 29, '']
]);
var options = {
width: 600,
height: 400,
legend: { position: 'top', maxLines: 3 },
bar: { groupWidth: '75%' },
isStacked: true
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
I tried morris.js, but I was unsuccessful.
Any help will be appreciated. Thanks!