Google Pie chart usage with Jquery inside a function? - javascript

I want to use google pie chart inside jquery and want the chart to be generated based on the condition.
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
var options = {title: 'Sample Chart'};
function drawChart() {
var data1 = new google.visualization.DataTable();
data1.addColumn('string', 'col1');
data1.addColumn('number', 'col2');
data1.addRow(["sample", 12]);
data1.addRow(["sample", 24]);
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data1, options);
}
Jquery function,
$.each(result, function(index) {
$("#tableContents").append("some html generation");
});
I want the data1 to be prepared during the loop of Jquery and draw at the end of the function. I see that if I takeout the data1 part of code (shown below) outside the function drawchart, I get
in console log,
Cannot read property 'DataTable' of undefined error
The data1 part of code I removed out of drawChart(),
var data1 = new google.visualization.DataTable();
data1.addColumn('string', 'col1');
data1.addColumn('number', 'col2');
data1.addRow(["sample", 12]);
data1.addRow(["sample", 24]);
Please help, thanks in advance.

You can parse the results into the DataTable like this:
function drawChart() {
var data1 = new google.visualization.DataTable();
data1.addColumn('string', 'col1');
data1.addColumn('number', 'col2');
$.each(result, function(index) {
$("#tableContents").append("some html generation");
// assumes results[index] has "col1Value" and "col2Value" properties
data1.addRow([results[index].col1Value, results[index].col2Value]);
});
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data1, options);
}

Related

How to get the last row of Google DataTable in javascript?

I have Temperature, Humidity and Time data and can fetch all the values from a database table for use in the DataTable. But I also want to extract the last set of values in the DataTable and print it in console.log.
I tried to print the console.log(data) as shown below and can see all values
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart', 'line']});
google.charts.setOnLoadCallback(drawLineColors);
function drawLineColors() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'time');
data.addColumn('number', 'Temperature');
data.addColumn('number', 'Humidity');
data.addRows([
<?php
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)){
echo "
['".$row['time']."',".$row['temp'].",".$row['hum']."],";
}
}
?>
]);
console.log(data);
var options = {
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Sensors Scale'
},
colors: ['#a52714', '#097138']
};
var chart = new
google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
You want to use .getValue(rowIndex, columnIndex) (see docs).
This way you can also easily pick and choose what you want, e.g. you might decide you want to use only the temperature, or the humidity values for example, not just the entire row.
let rowIndex = data.getNumberOfRows() - 1; //gets the row index of last row
let lastTime = data.getValue(rowIndex, 0); //gets the first column
let lastTemp = data.getValue(rowIndex, 1); //gets second column
let lastHum = data.getValue(rowIndex,2); //gets third column
console.log(`[${lastTime}, ${lastTemp}, ${lastHum}]`);

how to read data from an JSON file and pass it to google chart rows (javascript)

have the following function JSONChart()
it reads json data from var "allText" and should be able to parse the data and use it as row data for google charts.
Commenting out the adding row part displays the column data correctly with empty graph.
Need a way to parse the given sample data from a file and display it as row data in the google chart.
function JSONChart() {
google.charts.load('current', {'packages':['corechart']});
var data = new google.visualization.DataTable();
data.addColumn('string', 'Time stamp');
data.addColumn('number', 'CPU');
data.addColumn('number', 'MEMORY');
data.addColumn({type:'string', role:'annotation'});
data.addColumn({type:'string', role:'annotationText'});
var data1 = JSON.parse(allText);
var dataTableData = google.visualization.arrayToDataTable(data1);
data.addRows (dataTableData);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
// Set chart options
var options = {'title' : 'CPU & Memory',
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Percentage'
},
'width':1400,
'height':600,
curveType: 'function'
};
chart.draw(data, options);
}
window.onload = function() {
google.charts.setOnLoadCallback(JSONChart());
};
Sample JSON passed into variable "allText"
{"2017/11/03 01:06:51":{"SCREEN":" ABC ","MEMORY":" 32.0142% ","CPU":" 9.1% "},"2017/11/03 02:22:20":{"SCREEN":" XYZ ","MEMORY":" 31.101% ","CPU":" 10.3% "}
a few things...
1) arrayToDataTable expects a simple array, not a json object
it also returns an entire data table, which has already been created --> data
instead, convert each json object to an array,
then use addRows to add the data to the existing data table --> data
something like...
for (var date in data1) {
if (data1.hasOwnProperty(date)) {
chartData.push([
date,
parseFloat(data1[date].MEMORY.replace('%', '').trim()),
parseFloat(data1[date].CPU.replace('%', '').trim()),
data1[date].SCREEN,
'' // not sure what value you want to use here
]);
}
}
data.addRows(chartData);
2) google.charts.load -- this statement waits for the window / document to load, before calling the callback
no need for --> window.onload = function() {...
google.charts.load actually returns a promise,
so you can do something like...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
// draw chart code here...
3) when passing a callback function to setOnLoadCallback,
a reference to the function should be passed --> JSONChart
not the result of a function --> JSONChart() (remove parens)
4) recommend similar setup as following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Time stamp');
data.addColumn('number', 'CPU');
data.addColumn('number', 'MEMORY');
data.addColumn({type:'string', role:'annotation'});
data.addColumn({type:'string', role:'annotationText'});
var chartData = [];
var data1 = {"2017/11/03 01:06:51":{"SCREEN":" ABC ","MEMORY":" 32.0142% ","CPU":" 9.1% "},"2017/11/03 02:22:20":{"SCREEN":" XYZ ","MEMORY":" 31.101% ","CPU":" 10.3% "}};
for (var date in data1) {
if (data1.hasOwnProperty(date)) {
chartData.push([
date,
parseFloat(data1[date].MEMORY.replace('%', '').trim()),
parseFloat(data1[date].CPU.replace('%', '').trim()),
data1[date].SCREEN,
'' // not sure what value you want to use here
]);
}
}
data.addRows(chartData);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
var options = {'title' : 'CPU & Memory',
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Percentage'
},
height: 600,
curveType: 'function'
};
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google Chart Sorting vs Google Chart Editor

Please help! I am about to go insane over this! I have a Javascript for Google Chart that builds a table and a chart on the same dataset and when you sort the table the values on the chart get sorted as well. I also have a code that opens up the Google Charts Editor... which builds it's own chart. What I need is to merge these two functions. I need to build a table and a chart (that will get sorted as I sort the table) and when I open the Editor I need it to edit THAT chart (which will still be linked with sorting in the table) and NOT build a NEW chart.
Here are the 2 functions I have:
function drawSort() {
var data = new google.visualization.DataTable( <?= $jsonTable ?> );
var formatter = new google.visualization.NumberFormat({
prefix: '$'
});
formatter.format(data, 1); // Apply formatter to second column
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var table = new google.visualization.Table(document.getElementById('table_s_div'));
table.draw(view);
var chart = new google.visualization.BarChart(document.getElementById('chart_s_div'));
chart.draw(view);
google.visualization.events.addListener(table, 'sort',
function (event) {
data.sort([{
column: event.column,
desc: !event.ascending
}]);
chart.draw(view);
});
}
var chartEditor = null;
function loadEditor() {
// Create the chart to edit.
var data = new google.visualization.DataTable( <?= $jsonTable ?> );
var wrapper = new google.visualization.ChartWrapper({
chartType: 'LineChart',
dataTable: data,
options: {
'title': 'Number of Newly Opened Roles per <?echo $_SESSION['
Display ']?>',
'legend': 'none',
}
});
chartEditor = new google.visualization.ChartEditor();
google.visualization.events.addListener(chartEditor, 'ok', redrawChart);
chartEditor.openDialog(wrapper, {})
}
// On "OK" save the chart to a <div> on the page.
function redrawChart() {
chartEditor.getChartWrapper().draw(document.getElementById('chart_s_div'));
}

Google Visualization Charts ajax data

I'm trying to dynamically render a google visualization chart with an AJAX call in flask to set the data. User enters input then clicks a link which calls the ajax function to get the data. the "/ajax_test" view will return a json object but the problem I have is i don't know how to correctly pass the data back into the DataTable function. How do i pass the json data i'm getting from ajax to a variable for the drawchart function?
Chart function:
<script type="text/javascript">
function drawChart(){
var data = new google.visualization.DataTable(jsondata);
var options = {
explorer: {},
}; //end options
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
Ajax function:
<script type=text/javascript>
$(function() {
$('a#DrawChart').bind('click', function() {
$.getJSON($SCRIPT_ROOT + '/ajax_test',
{//input data sent to view}
, function(data) {
var jsondata = data.test_json;
drawChart();
});
return false;
});
});
</script>
This method doesn't know where jsondata comes from:
function drawChart() {
var data = new google.visualization.DataTable(jsondata);
...
}
Add jsondata as a parameter:
function drawChart(jsondata) {
var data = new google.visualization.DataTable(jsondata);
...
}
And then in your Ajax call pass jsondata to the method:
function(data) {
var jsondata = data.test_json;
drawChart(jsondata);
}
I have done something similar using the following code, this is a jinja2 example, so you have do adapt your code (change the way jsonData var is initialized):
<script type="text/javascript">
//load the Google Visualization API and the chart
google.load('visualization', '1', {'packages': ['corechart']});
google.setOnLoadCallback (createChart);
var jsonData = {{ value_columns | tojson | safe }}
function createChart() {
var dataTable = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.LineChart(document.getElementById('chart'));
//define options for visualization
var options = {is3D: 'no', title: 'Some Title' };
attachRedrawForTab(chart, dataTable, options);
attachRedrawForAccord(chart, dataTable, options);
//draw our chart
chart.draw(dataTable, options);
}
</script>

Google Chart API - using JS to dynamicaly add data

Morning, I have the data hidden in the page but im not sure how to add it to the addRows function.
This is what I have:
google.load("visualization", "1", {packages:["corechart"]});
$(document).ready(function(){
var rowArray = [];
$('input[name=device_name]').each(function(i){
var name = $(this).val();
var amount = $(this).next().val();
rowArray.push(["'" + name + "'", amount]);
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Device');
data.addColumn('number', 'Amount');
data.addRows( rowArray );
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, {
width: 600,
height: 340,
title: 'Handheld Device Usage',
hAxis: {
title: 'Mobile Device Name',
titleTextStyle: {
color: '#404040'
}
}
});
}
});
Can anyone see where im going wrong?
Regards,
Phil
Maybe this will work:
$('input[name=device_name]').each(function(i){
var name = $(this).val();
var amount = ($(this).next().val() * 1);
rowArray.push([name, amount]);
});
the problem is that amount is a string... I've seen that you're using a js framework so you could probably make a console.log(rowArray); to debug.
a good way to correct that would be if you change this:
var amount = $(this).next().val().toInt();
I've tested it http://jsfiddle.net/TfsFT/1/ and its working. Although i had to change a few things cause i was using Mootools.. and i didn't have the html code :P
Good Luck!

Categories

Resources