Google Chart Sorting vs Google Chart Editor - javascript

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

Related

Insert data from database to google chart codeigniter

I want to insert data to get sales report from two table into google chart. I have tried join query in model page, but the result is No Data in pie chart div.
Data from table sales is like below
id | person_name | sales_id | status
1 Michael 2 1
2 Daniel 2 3
3 James 2 1
4 Ricky 1 2
5 Martin 1 3
The data from table status is like below
id | status | color
1 Meeting #f00630
2 Presentation #f2478f
3 Proposal Sent #170303
4 Invoice #7cb342
5 Lost #fe0725
I need to insert data status type, total status (in number), and color status into google pie chart based on sales id. I need to change data which I write manually like below
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Type', 'Total'],
['Meeting', 2],
['Presentation', 0],
['Proposal Sent', 1],
['Invoice', 0],
['Lost', 0]
]);
var options = {
is3D: true,
colors: ['#f00630', '#f2478f', '#170303', '#7cb342', '#fe0725']
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Here is the script I have tried in model page
public function getAllStatus()
{
$this->db->select('status');
$this->db->from('sales');
$this->db->join('sales_status', 'sales_status.id = sales.status');
$this->db->where('sales_id', $id);
return $query = $this->db->get();
}
Here's script in controller page
$data['sales'] = $this->Sales_model->getAllStatus()->result();
And here's the script in view page
var data = google.visualization.arrayToDataTable([
['Type', 'Total'],
<?php
foreach ($sales as $sale){
echo "['".$sale->name."',".$sale->count."],";
}
?>
]);
<div id="chart_div" style="width: 100%; "></div>
Do you know where's I need to fix ?
Thank you
The chart expects JSON objects with the data. You can try to build JSON-like structures with loops like you did, but it's much simpler to just output the JSON objects.
In your view, before the call to the chart is made:
var first_data = <?php echo json_encode($your_first_var); ?>;
var second_data = <?php echo json_encode($your_second_var); ?>;
then, when you actually invoke the JS that will draw the chart:
function drawChart() {
var data = google.visualization.arrayToDataTable(first_data);
var options = {
is3D: true,
colors: second_data
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}

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 Pie chart usage with Jquery inside a function?

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

Google Charts Tooltip

I am using a Google Pie Chart in my website to show some data of company expenses. The chart gives me nice tooltips as I hover over the slices. It says for example 27% and gives the number of expense as 522552225.00 for example. What I would like to do is to get the number formatted as it is hard to read when the number is large. I would like to have this instead 522,552,225.00.
The problem is that the number comes from database.
Is there a solution to this?
Thanks!
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Label","Value"],
<?php echo $MyDataArrayAsString; ?>
]);
var formatter = new google.visualization.NumberFormat({pattern:'#,###.00'});
// format column 1 of DataTable "data"
formatter.format(data, 2);
var options = {"width":<?php echo $params->get('width')?>,
"height":<?php echo $params->get('height')?>,
"tooltip": {"trigger": '<?php echo $params->get('tooltip')?>' },
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
Use a NumberFormatter on the appropriate DataTable column:
var formatter = new google.visualization.NumberFormat({pattern: '#,###.00'});
// format column 1 of DataTable "data"
formatter.format(data, 1);

Categories

Resources