google visualisation annotated timeline: how to set roles using PHP json roles - php

I am trying to plot two different time series using annotated timeline and PHP by adding roles - the second timeseries will have its own datetime type and role domain. Here is the index.php file:
<script type='text/javascript'>
google.load('visualization', '1', {'packages':['annotatedtimeline']});
google.setOnLoadCallback(drawChartSeptTEC);
function drawChartSeptTEC(){
var json = $.ajax({
url: "get_json_forecast.php",
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(json);
var chart = new google.visualization.AnnotatedTimeLine(document.getElementById('chart_div'));
chart.draw(data, {displayAnnotations: true});
}
// setInterval(drawChartSeptTEC, 59000 );
</script>
and the server side:
<?php
$tempcols=array();
$tempcols[] =array('type' => 'datetime','role' => 'domain');
$tempcols[] =array('type' => 'number','role' => 'data','label'=>'polynomial');
$tempcols[] =array('type' => 'number','role' => 'interval');
$tempcols[] =array('type' => 'number','role' => 'interval');
$tempcols[] =array('type' => 'datetime','role' => 'domain');
$tempcols[] =array('type' => 'number','role' => 'data','label'=>'spectral');
$table['cols'] = $tempcols;
$rows = array();
$pg_result = pg_query($link,$query);
pg_close($link);
while ($row = pg_fetch_assoc($pg_result)) {
$temp = array();
$correctDateTime = substr_replace($row['time'], ( substr($row['time'],5,2) -1 ) ,5,2);
$temp[] = array('v' => "Date(".$correctDateTime.")");
$temp[] = array('v' => (float) $row['f2poly']);
$temp[] = array('v' => (float) $row['f2polydev']);
$temp[] = array('v' => (float) $row['f2polydev']);
$temp[] = array('v' => "Date(".$correctDateTime.")");
$temp[] = array('v' => (float) $row['f2spec']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
echo $jsonTable;
?>
The console error reports:
Error: each values column may be followed by one or two annotation columns. Column number 4 is of type datetime.
The visualisation works when I remove the second domain column.
The interval roles (that is the error bars) are not recognised as well. Which simplifies the question to: How do we configure roles using PHP?

annotated time line does not support roles. In order to achive the result, one needs to use another visualisation, for example:
....
google.load('visualization', '1', {'packages':['corechart']});
....
and to plot the data:
...
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
...
however, this chart does not support a second domain role, therefore you need to use one domain (or independent variable, say the x-axis) and use for y-values null if the domain x-values have no corresponding y-value for both data sets. In this case, and if you want to use lines, you need to set the option:
interpolateNulls: true,
in your draw() function.
Another option is to use dygraph which is faster than line chart.

Related

Googe Pie Chart PHP

Why can't I add data to my google pie chart?
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
<?php
foreach($piechartcaloy as $value){
echo "['".$value['product_name']."',".$value['TEST']."],";
}
?>
]);
var options = {
title: 'TOP 10 products'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart2'));
chart.draw(data, options);
}
it vanished the pie chart when i add the
<?php
foreach($piechartcaloy as $value){
echo "['".$value['product_name']."',".$value['TEST']."],";
}
?>
but if i add a normal
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['test',1]
]);
it work but why does my php does not working although i tried to print_r($data);die; my data array it shows like this
Array ( [piechartcaloy] => Array ( [0] => Array ( [product_name] => REG Okinawa [TEST] => 1 ) [1] => Array ( [product_name] => French Fries [TEST] => 0 ) ) )
It has values in it but why can't I populate it? What is wrong in my loop in the pie chart?
i already solved the answer and noticed that the array was having a space so i tried using trim(); and it works trim removes extra spaces that fix the problem.
here is the code i implement
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
<?php
foreach($piechartcaloy as $value){
echo "['".trim($value['product_name'])."',".trim($value['TEST'])."],";
}
?>
]);
var options = {
title: 'TOP 10 Fast Moving products'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart2'));
chart.draw(data, options);
}

Can PHPword show Pie Chart in percenage with two decimals?

I use PHPword class to create Word file in PHP.
Can you create Pie chart to show value in percentage with two decimals?
$c3 = array('Expensive kW', 'Cheap kW');
$s3 = array($expensive, $cheap);
$tablePie2Charts = $section->addTable('Chart');
$tablePie2Charts->addRow();
$stylePie2Chart = array(
'width' => Converter::inchToEmu(5),
'height' => Converter::inchToEmu(3),
'valueAxisTitle' => 'Last month consumed in kW',
'showLegend' => true,
'dataLabelOptions' => array(
'showCatName' => false,
'showVal' => false,
'showPercent' => true
)
);
$c1 = $tablePie2Charts->addCell()->addChart('pie', $c3, $s3, $stylePie2Chart);
I also encountered the same problem.But i can't find an api to support it.
And here my solution:
edit the file /PhpOffice/Phpword/Writer/Word2007/Part/Chart.php
near the line 250. Insert the code
$xmlWriter->writeElementBlock("c:numFmt",['formatCode'=>'0.00%','sourceLinked'=>'0']);
between
$xmlWriter->startElement('c:dLbls');
and
foreach ($style->getDataLabelOptions() as $option => $val) {
It finally look like that:
$xmlWriter->startElement('c:dLbls');
$xmlWriter->writeElementBlock("c:numFmt",['formatCode'=>'0.00%','sourceLinked'=>'0']);
foreach ($style->getDataLabelOptions() as $option => $val)
if you just want it in pie chart and you should:
if ('pie' === $this->element->getType()){
$xmlWriter->writeElementBlock("c:numFmt",['formatCode'=>'0.00%','sourceLinked'=>'0']);
}
You can change the formatCode like 0.0% 0.00% 0.000% whatever you want.
If someone find the better way,plz tell me,thanks.

Fetch Data from Oracle using OCI 8 and create Google Pie Chart

Fetch Data from Oracle:
echo "<br/>Self User data<br/>";
$curs = oci_new_cursor($conn);
$varin1 = "111"; //employee_id
$varin2 = "FEB-2015"; //month_year
$varin3 = "1";
$stid = oci_parse($conn, "begin WEEKLY_EMPLOYEE_DETAILS(:varIn1,:varIn2,:cursbv); end;");
oci_bind_by_name($stid, ":varIn1", $varin1);
oci_bind_by_name($stid, ":varIn2", $varin2);
oci_bind_by_name($stid, ":cursbv", $curs, -1, OCI_B_CURSOR);
oci_execute($stid);
oci_execute($curs); // Execute the REF CURSOR like a normal statement id
echo "<pre>";
while (($row = oci_fetch_array($curs, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
print_r($row) . "<br />\n";
}
oci_free_statement($stid);
oci_free_statement($curs);
Ouput of above code:
Self User data
Array
(
[EMPLOYEEID] => 111
[EMPLOYEENAME] => John Doe
[TOTAL_HOURS] => 24
[STATUS] => 1
[WEEK_ID] => 2
)
Array
(
[EMPLOYEEID] => 111
[EMPLOYEENAME] => John Doe
[TOTAL_HOURS] => 20
[STATUS] => 2
[WEEK_ID] => 3
)
Array
(
[EMPLOYEEID] => 111
[EMPLOYEENAME] => John Doe
[TOTAL_HOURS] => 40
[STATUS] => 2
[WEEK_ID] => 4
)
Google Pie chart 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([
['Work', 'Hours per Day'],
['Week 1', 25],
['Week 2', 25],
['Week 3', 25],
['Week 4', 25]
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
How can I show the data fetched in form of pie chart. If there are 5 weeks in a month it will display the pie chart slice likewise. Along with it, it should also display hours for that week which are coming in array.
The pie chart looks great. You could pass the php variables to javascript and use them in the array.
var week1 = <?php echo json_encode($week1['TOTAL_HOURS']); ?>;
etc..
var data = google.visualization.arrayToDataTable([
['Work', 'Hours per Week'],
['Week 1', week1],
['Week 2', week2],
['Week 3', week3],
['Week 4', week4]
]);
It would be cleaner to put these variables in an array, and do a check first how many weeks there are in the month. You could do the same for the daily hours by fetching the daily employee details from the oracle database (if they exist).
To read more about passing variables to javascript:
How to pass variables and data from PHP to JavaScript?

JSON from mySQL and Coloring in Google Charts

I would like to get some help with coloring data differently in with google chart. I'm trying to compare two domains with date and rank value.
If I leave out the 'domain' data and just have date and value data, it will display a chart with the date data on the y-axis and the value data on the x-axis. I would like to use the domain data in my table to differentiate the data I'm comparing, one domain in one color vs. another domain in another color in a bar chart with the legend identifying the domain.
Basically using the code below I get the following error:
All series on a given axis must be of the same data type
If there's different and or easier way of going about this let me know.
Table Structure:
Column Type Null Default Comments
date text No
value text No
domain text No
Here's what I use to change my mysql data into Google friendly JSON:
<?php
/* $server = the IP address or network name of the server
* $userName = the user to log into the database with
* $password = the database account password
* $databaseName = the name of the database to pull data from
*/
$host="127.0.0.1"; //replace with your hostname
$username="XXXXXXX"; //replace with your username
$password="XXX"; //replace with your password
$db_name="KYW_data"; //replace with your database
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name") or die ("cannot select DB");
mysql_select_db($db_name, $con);
// write your SQL query here (you may use parameters from $_GET or $_POST if you need them)
$query = mysql_query('SELECT date, value FROM KYW_Compete_rank');
$table = array();
$table['cols'] = array(
/* define your DataTable columns here
* each column gets its own array
* syntax of the arrays is:
* label => column label
* type => data type of column (string, number, date, datetime, boolean)
*/
array('label' => 'date', 'type' => 'string'),
array('label' => 'value', 'type' => 'number'),
array('label' => 'value', 'type' => 'string')
// etc...
);
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$temp = array();
// each column needs to have data inserted via the $temp array
$temp[] = array('v' => $r['date']);
$temp[] = array('v' => $r['value']);
$temp[] = array('v' => $r['domain']);
// etc...
// insert the temp array into $rows
$rows[] = array('c' => $temp);
}
Code for Displaying Google Chart:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "fetch.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
new google.visualization.BarChart(document.getElementById('visualization')).
draw(data,
{title:"Rank Standings",
width:600, height:400,
vAxis: {title: "Year and Month"},
hAxis: {title: "Rank"}}
);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="visualization"></div>
</body>
</html>
To get the legend to display two different series, you have to split your data into two columns. You can use SQL like this to split your data:
SELECT
date,
SUM(IF(<condition for series 1>, value, 0)) AS value_1,
SUM(IF(<condition for series 2>, value, 0)) AS value_2
FROM KYW_Compete_rank
GROUP BY date
and then populate your DataTable:
$table = array(
'cols' => array(
array('label' => 'date', 'type' => 'string'),
array('label' => 'value 1', 'type' => 'number'),
array('label' => 'value 2', 'type' => 'number')
)
'rows' => array()
);
while($r = mysql_fetch_assoc($query)) {
$data['rows'][] = array('c' => array(
array('v' => $r['date']),
array('v' => $r['value_1']),
array('v' => $r['value_2'])
));
}
echo json_encode($data, JSON_NUMERIC_CHECK);

Google charts column graph from MySql database

The real question is how do I populate a Google charts datatable form a MySql query when a date is used for the first column?
I am trying to create a column chart using the Google Charts API. The problem is that the data is time series data. There are many dates represented. The way that this is done to create the data table is to assign column 0 to the date and each subsequent column represents the data being measured. That information is derived from the documentation. I just can't figure out how to get the data to assign to the subsequent columns. I have researched this extensively now and there are some answers that are close, but I can't make them work for this. Here is the code that is currently generating my chart data table:
$invArr = array('cols' => array(
array('label' => 'date', 'type' => 'date'),
array('label' => 'SKU', 'type' => 'number')),
'rows' => array());
while($row = mysql_fetch_row($query)) {
$invArr['rows'][] = array('c' => array(array('v' => $row[0]), array('v' => $row[1])));
}
I understand from the Google charts documentation that column 0 is always the date for continuous data. Each subsequent column is the data that is being measured, in this case ths SKU numbers. I need to have the first array in each row represent the date and the subsequent arrays represent the qtyoh data. I don't know how to do that.
I researched this for several days and I was finally able to solve the problem by piecing together answers to many different questions.
I started by querying the distinct dates and placing them into an array. The way this is done is very important because the date is a string when json encoded. It is important to parse it out and pass it in the Date(year,month,day) format exactly. It is also important that later on you use a variable to represent the date.
$dateArray = array();
while($row = mysql_fetch_row($queryDates)) {
$dtArray = explode('-',$row[0]);
$day = (int) $dtArray[1];
$month = ((int) $dtArray[0])-1;
$year = (int) $dtArray[2];
$dateArray[] = "Date($year, $month, $day)";
}
I then set up the columns for the table by looping through a query of the SKU's.
$invArr = array(
'cols' => array(
array('label' => 'Date', 'type' => 'date')
)
);
while($row = mysql_fetch_row($querySkus)) {
$invArr['cols'][] = array('label' => $row[0], 'type' => 'number');
}
I then query the quantities and place them into an array. I then loop through each value and populate the table array ($inVarr).
$quantities = array();
while($row = mysql_fetch_row($queryQty)) {
$quantities[] = (int) $row[0];
}
$qtyCounter = 0;
for($i=0;$i<count($dateArray);$i++) {
$invArr['rows'][] = array(
'c' => array(
array('v' => $dateArray[$i]),
array('v' => $quantities[$qtyCounter]),
array('v' => $quantities[$qtyCounter+1]),
array('v' => $quantities[$qtyCounter+2])
)
);
$qtyCounter=$qtyCounter+3;
}
I can then just echo the json encoded array which will return the data for the data table.
echo json_encode($invArr);
I believe that this is a bit clunky, but it works.

Categories