I'm just trying to figure out to format my labels to be shown as a currency and not just a number:
echo ' <script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn("string", "ZipCode");
data.addColumn("number", "Sales");
data.addRows('.$count.');';
$i = 0;
foreach ($results as $r) {
$p = (($r->report_trans_amount / $total) * 100);
$pd = strval(number_format($p, 1));
echo ' data.setValue(' . $i . ', 0, "' . $r->member_address_zip_code .
' - ' . $pd . '%");';
echo ' data.setValue(' . $i . ', 1, ' . $r->report_trans_amount . ');';
$i++;
}
echo ' var chart = new google.visualization.PieChart(
document.getElementById("chart_div"));
chart.draw(data, {width:900, height:500, is3D:true});
}
</script>
<div id="chart_div"></div>
';
I would like the Sales column to be shown as a USD currency value. How can I do that? I see how to do it using the URL request, but that does not help this situation.
I just can't seem to find any good example on this.
it looks like you might want to look at setFormattedValue
http://code.google.com/apis/chart/interactive/docs/reference.html#DataTable_setFormattedValue
and for the format stuff look at
http://code.google.com/apis/chart/interactive/docs/reference.html#formatters
I haven't tried this out, but from what I can tell this could work for you:
echo '
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn("string", "ZipCode");
data.addColumn("number", "Sales");
data.addRows('.$count.');
var formatter = new google.visualization.NumberFormat({prefix: \'$\'});
formatter.format(data, 1);';
$i = 0;
foreach($results as $r){
$p = (($r->report_trans_amount / $total) * 100);
$pd = strval(number_format($p, 1));
echo 'data.setValue('.$i.', 0, "'.$r->member_address_zip_code.' - '.$pd.'%");';
//echo 'data.setFormattedValue('.$i.', 1, formatter);'; // might not need this with the formatter.format above
echo 'data.setValue('.$i.', 1, '.$r->report_trans_amount.');';
$i++;
}
echo ' var chart = new google.visualization.PieChart(document.getElementById("chart_div"));
chart.draw(data, {width:900, height:500, is3D:true});
}
</script>
<div id="chart_div"></div>
';
references:
http://code.google.com/p/google-visualization-api-issues/issues/detail?id=282
Related
I need to implement google chart on my project but it returns error as i said..here is my view code
String like months as well as days not working, numbers are okey..
I got this data from codeigniter controller and model, any hope for the answer.
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1.1", {packages: ['bar', 'timeline']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
[{type: 'string', label: 'Days'}, {type: 'number', label: 'Viewers'}],
<?php
foreach ($chart_data as $data) {
$date = strtotime($data->view_time);
$day = date('D',
$date); //mon,tue
echo '[' . $day . ',' . $data->id . '],';
}
?>
]);
var options = {
chart: {
title: 'App viewers',
subtitle: 'Viewers: <?php echo 'Sun' . '-' . 'Sat'; ?>',
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, options);
}
</script>
New PHP user here. I have a database that looks like this:
id name day1 day2 day3 day4 day5
1 nam1 5 9 15 50 45
2 nam2 51 12 54 78 56
3 nam3 12 145 78 49 58
The database contains thousands of users. Each number in the table represents the amount of daily activities per user. We need a table which looks like this
id name day1 day2 day3 day4 day5 chart
1 nam1 5 9 15 50 45
2 nam2 51 12 54 78 56
3 nam3 12 145 78 49 58
We want to draw a google line chart in the last column for each user. This is the code to generate the chart:
<?php
$result = mysqli_query($c,"SELECT * from users limit 100");
$row = mysqli_fetch_array($result);
$d1=$row['day1']; $d2=$row['day2']; $d3=$row['day3']; $d4=$row['day4']; $d5=$row['day5'];
//// that's the data that get loaded into Google Charts(no axis label) ////
$data="[['','day'],['',".$d1."],['', ".$d2."],['', ".$d3. "],['', ".$d4."],['', ".$d5. "]]";
?>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo $data ?>);
var options = {
title: 'User Activities',
curveType: 'function',
width:200,
height:150,
legend: 'none'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<?php echo "<table border='1'>
<tr>
<th>id</th>
<th>name</th>
<th>charts</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>
<div id=\"chart_div\" style=\"width:200; height:150\"></div></td>";
echo "</tr>";
}
echo "</table>"; ?>
</body>
</html>
This code generates only one chart for user id=2. The first user, and the other users are ignored. How do you get a chart for each row? Thanks four help.
The easiest way requires a bit of rearranging your code to make it work:
<html>
<head>
</head>
<body>
<table border='1'>
<tr><th>id</th><th>name</th><th>charts</th></tr>
<?php
$result = mysqli_query($c,"SELECT * from users limit 100");
$data = array(array('', 'Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'));
$i = 0;
while($row = mysqli_fetch_array($result)) {
echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td><td><div id='chart_div_{$i}' style='width:200; height:150'></div></td></tr>";
$data[] = array('', $row['day1'], $row['day2'], $row['day3'], $row['day4'], $row['day5']);
$i++;
}
?>
</table>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>);
var options = {
title: 'User Activities',
curveType: 'function',
width: 200,
height: 150,
legend: 'none'
};
var charts = [];
var views = [];
for (var i = 0; i < data.getNumberOfRows(); i++) {
views.push(new google.visualization.DataView(data));
views[i].setRows([i]);
charts.push(new google.visualization.LineChart(document.querySelector('#chart_div_' + i)));
charts[i].draw(views[i], options);
}
}
</script>
</body>
</html>
That won't produce very nice LineCharts, however, as you will have 5 lines with 1 point each. If you are looking for a single line that spans 5 days, then this is how you want to set it up:
<html>
<head>
</head>
<body>
<table border='1'>
<tr><th>id</th><th>name</th><th>charts</th></tr>
<?php
$result = mysqli_query($c,"SELECT * from users limit 100");
$data = array(
array('Day'),
array('Day 1'),
array('Day 2'),
array('Day 3'),
array('Day 4'),
array('Day 5')
);
$i = 0;
while($row = mysqli_fetch_array($result)) {
echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td><td><div id='chart_div_{$i}' style='width:200; height:150'></div></td></tr>";
$data[0][] = "Daily activities for {$row['name']}";
$data[1][] = $row['day1'];
$data[2][] = $row['day2'];
$data[3][] = $row['day3'];
$data[4][] = $row['day4'];
$data[5][] = $row['day5'];
$i++;
}
?>
</table>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>);
var options = {
title: 'User Activities',
curveType: 'function',
width: 200,
height: 150,
legend: 'none'
};
var charts = [];
var views = [];
for (var i = 0; i < data.getNumberOfColumns() - 1; i++) {
views.push(new google.visualization.DataView(data));
views[i].setColumns([0, i + 1]);
charts.push(new google.visualization.LineChart(document.querySelector('#chart_div_' + i)));
charts[i].draw(views[i], options);
}
}
</script>
</body>
</html>
Hi I am trying for google stacked column charts. But I was getting the following error which I could not able to solve it. The error is "Uncaught TypeError: Cannot read property 'type' of null "
Here my code
<html>
<head>
<title></title>
</head>
<?php $con=mysql_connect("localhost","root", "innernet") or die("Failed to connect with database!!!!");
mysql_select_db("mobiledb", $con);
$user= $_GET['user'];
//echo $user;
$response["cols"] = array();
// $news = array();
//$news["id"] = "";
//$news["label"] = "ID";
//$news["type"] = "string";
//array_push($response["cols"], $news);
array_push($response["cols"], $news);
$news = array();
//$news["id"] = "";
//$news["label"] = "Q9a";
$news["type"] = "number";
array_push($response["cols"], $news);
$news = array();
//$news["id"] = "";
//$news["label"] = "Q9b";
$news["type"] = "number";
array_push($response["cols"], $news);
// $news = array();
// $news["id"] = "";
//$news["label"] = "ts";
// $news["type"] = "number";
// array_push($response["cols"], $news);
$result = mysql_query("SELECT `Q9a`, `Q9b` FROM goaltest WHERE id='$user'") or die(mysql_error());
if (mysql_num_rows($result) > 0)
{
$response["rows"] = array(); $table = array(); $rows = array();
while ($row = mysql_fetch_array($result))
{
$temp = array();
//$temp[] = array('v' => (string) $row['id']);
$temp[] = array('v' => (int) $row['Q9a']);
$temp[] = array('v' => (int) $row['Q9b']);
//$temp[] = array('v' => (int) $row['ts']);
array_push($response["rows"], array('c' => $temp));
}
//echo json_encode($response);
}
?>
<!--Load the AJAX API -->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
google.load("visualization", "1.0", {packages:["imagechart"]});
</script>
<script type='text/javascript'>
google.setOnLoadCallback(drawChart);
function drawChart() {
var response = '<?php echo json_encode($response); ?>'; alert(' hi ' + response);
var obj = eval ("(" + response + ")");
var dataTable = new google.visualization.DataTable(response);
var options = {cht: 'bvs', chs: '300x125', colors:['#4D89F9','#C6D9FD'],
chds:'0,160', chxl:'0:|oranges|apples|pears|bananas|kiwis|'};
var chart = new google.visualization.ImageChart(document.getElementById('bar_div'));
chart.draw(dataTable, options);
}
</script>
<body>
<div id='bar_div'></div>
</body>
</html>
So please any one tell me how to solve this
<html>
<head>
<title></title>
</head>
<!--Load the AJAX API -->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
google.load("visualization", "1.0", {packages:["imagechart"]});
</script>
<script type='text/javascript'>
google.setOnLoadCallback(drawChart);
function drawChart() {
var response = '{"cols":[null,{"type":"number"},{"type":"number"}],"rows":[{"c":[{"v":12},{"v":23}]},{"c":[{"v":37},{"v":55}]}]}'; alert(' hi ' + response);
var obj = eval ("(" + response + ")");
var dataTable = new google.visualization.DataTable(response);
var options = {cht: 'bvs', chs: '300x125', colors:['#4D89F9','#C6D9FD'],
chds:'0,160', chxl:'0:|oranges|apples|pears|bananas|kiwis|'};
var chart = new google.visualization.ImageChart(document.getElementById('bar_div'));
chart.draw(dataTable, options);
}
</script>
<body>
<div id='bar_div'></div>
</body>
</html>
(#asgallant has probably guessed right already.) In your first array_push(... $news) The $news is not yet defined. Consequently, the first array element under the "cols" property in the response variable is null. Maybe you just want to comment out that first array_push.
I want to generate graph for my static data. I am using Google Chart for doing this. Here is the google 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([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
But i want to put my code in this. I am not getting how to do it. Here is my code
<?php
echo '<div align="center" style="width:100%; padding-top:20px;">
<table width="100%" cellspacing="0" cellpadding="0" border="0">
<tr>
<td class=tddash>10 latest purchase orders</td>
</tr>
<tr>
<td>';
$SQL = 'SELECT purchorders.orderno,
suppliers.suppname,
purchorders.orddate,
purchorders.deliverydate,
purchorders.initiator,
purchorders.requisitionno,
purchorders.allowprint,
purchorders.status,
suppliers.currcode,
currencies.decimalplaces AS currdecimalplaces,
SUM(purchorderdetails.unitprice*purchorderdetails.quantityord) AS ordervalue
FROM purchorders
INNER JOIN purchorderdetails
ON purchorders.orderno = purchorderdetails.orderno
INNER JOIN suppliers
ON purchorders.supplierno = suppliers.supplierid
INNER JOIN currencies
ON suppliers.currcode=currencies.currabrev
WHERE purchorders.orderno=purchorderdetails.orderno
GROUP BY purchorders.orderno,
suppliers.suppname,
purchorders.orddate,
purchorders.initiator,
purchorders.requisitionno,
purchorders.allowprint,
purchorders.status,
suppliers.currcode,
currencies.decimalplaces LIMIT 5';
$SalesOrdersResult2 = DB_query($SQL,$db);
$Total = 0;
echo '<table width="100%" celpadding="2" class="selection">';
echo '<tbody><tr><th> Supplier </th><th>Order Date</th><th>Delivery Date</th><th>Initiator</th><th>Order Total</th><th>Status</th></tr></tbody> ';
$k=0;
while ($row = DB_fetch_array($SalesOrdersResult2))
//while ($row = mysql_fetch_array($SalesOrdersResult))
{
if ($k == 1){
echo '<tr class="EvenTableRows">';
$k = 0;
} else {
echo '<tr class="OddTableRows">';
$k = 1;
}
$FormatedOrderValue2 = locale_number_format($row['ordervalue'],$row['currdecimalplaces']);
$Total += $row['ordervalue'];
//$FormatedOrderValue1 = locale_number_format($myrow['ordervalue'],$_SESSION['CompanyRecord']['decimalplaces']);
$FormatedOrderDate1 = ConvertSQLDate($row['orddate']);
$FormatedDelDate1 = ConvertSQLDate($row['deliverydate']);
echo ' <td> ' . $row['suppname'] . ' </td>';
echo ' <td>$FormatedOrderDate1</td><td>$FormatedDelDate1</td><td> ' . $row['initiator'] . ' </td><td>$FormatedOrderValue2</td><td> ' . $row['status'] . ' </td> ';
}
echo '<tr><td colspan="3">Total---</td><td colspan="2">$Total</td></tr></tbody>';
echo '</table></td>';
echo' </tr>
</table>
</div>';
Can somebody plz help me in this?
* EDITED *
echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>';
echo ' <script type="text/javascript">
function drawChart() {
var jsonData = $.ajax({
url: "1getData.php",
dataType:"json",
async: false
}).responseText;
alert(jsonData);
var data = new google.visualization.DataTable(jsonData);
var view = new google.visualization.DataView(data);
view.setColumns([0, 3]);
var chart = new google.visualization.ColumnChart(document.getElementById("chart_div"));
chart.draw(view, {width:400, height:240});
}
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
</script>';
echo '</head>';
<div id="chart_div" ></div>
1getData.php
<?php
$PageSecurity=0;
include('includes/session.inc');
if (!isset($RootPath)){
$RootPath = dirname(htmlspecialchars($_SERVER['PHP_SELF']));
if ($RootPath == '/' or $RootPath == "\\") {
$RootPath = '';
}
}
$SQL = "SELECT workorders.wo, woitems.stockid, stockmaster.description, stockmaster.decimalplaces, woitems.qtyreqd, woitems.qtyrecd, workorders.requiredby, workorders.startdate
FROM workorders
INNER JOIN woitems ON workorders.wo = woitems.wo
INNER JOIN stockmaster ON woitems.stockid = stockmaster.stockid
ORDER BY workorders.wo";
$searchresult = DB_query($SQL, $db);
$table=array();
$table['cols']=array(
array('label'=>'ITEM', type=>'string'),
array('label'=>'Description', type=>'string'),
array('label'=> 'QTY Required', type=>'number'),
array('label'=>'QTY Outstanding', type=>'number')
);
$rows=array();
while ($row = DB_fetch_array($searchresult))
{
$qreq = locale_number_format($row['qtyreqd'],$row['decimalplaces']);
$qout = locale_number_format($row['qtyreqd']-$row['qtyrecd'],$row['decimalplaces']);
$temp=array();
$temp[]=array('v' => $row['stockid']);
$temp[]=array('v' => $row['description']);
$temp[]=array('v' => $row['qtyreqd']);
$temp[]=array('v' => ($row['qtyreqd']-$row['qtyrecd']));
$rows[]=array('c' => $temp);
}
$table['rows']=$rows;
$jsonTable = json_encode($table);
print $jsonTable;
?>
but it displays only two columns, where as i want to display 3
JAVA SCRIPT
<script type="text/javascript">
function drawChart() {
var jsonData = $.ajax({
url: "1getData.php",
dataType:"json",
async: false
}).responseText;
alert(jsonData);
var data = new google.visualization.DataTable(jsonData);
var view = new google.visualization.DataView(data);
view.setColumns([0,3]);
var chart = new google.visualization.ColumnChart(document.getElementById("chart_div"));
chart.draw(view, {width:400, height:240});
}
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
</script>
Your line view.setColumns([0, 3]) tells Google charts to only display the first and fourth column in your data. Add the columns you want to display to the array.
I have been trying to plot these on a scatter chart using google api. But it doesn't seem to work.
S.No:1 Price:0.632 Volume:10.26
S.No:2 Price:0.631 Volume:10
S.No:3 Price:0.631 Volume:20
S.No:4 Price:0.631 Volume:4.65
I have hundred entries like this, which represents the bitcoin value.
I want to plot it in a way that price in on the vertical axis and Serial no. in horizontal axis. The volume will define the diameter of the circle.
<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 = new google.visualization.DataTable();
data.addColumn('number', 'Transactions');
data.addColumn('number', 'Price');
data.addRows(6);
data.setValue(1, 0.632, 10.26);
data.setValue(2, 0.631, 10);
data.setValue(3,0.631, 20);
data.setValue(4, 0.631, 4.65);
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240,
title: 'Bitcoins Transaction Prices',
hAxis: {title: 'Transactions', minValue: 1, maxValue: 100},
vAxis: {title: 'Price', minValue: 0, maxValue: 5},
legend: 'none'
});
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
This returns a blank page for me. Whats possibly wrong? I follow this example.
My php code from which i get the values is given below.
<?php
//get the unix time stamp of day 30 days back from today
$last_thirty = strtotime('-30 days');
//get the unix time stamp of day 1 month back from today
$last_month = strtotime("-1 month");
//get the data using bitcoinchart http api
$json = file_get_contents('http://bitcoincharts.com/t/lasttrades.json?limit=10&since=' . $last_month);
//decode json to php array
$data = json_decode($json);
$no = 1;
//loop through it
foreach ($data as $item) {
$sn = "S.No:".$no . "";
$price = "Price:{$item->price}";
$volume = "Volume:{$item->volume}";
$no++;
echo $sn . "<br/>";
echo $price . "<br/>";
echo $volume . "<br/>";
} ?>
The complete documentation can be found here.
http://code.google.com/apis/chart/interactive/docs/customizing_charts.html