How can i plot a google scatter chart using php - php

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

Related

how to use mysql data on google charts

I am trying to create a bar chart using google charts and mysqli. But my code is not working when I try to insert php in the googlecharts it is no longer showing up on the webpage.
my code:
<!--GOOGLE CHARTS-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></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 corechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
//PHP
<?php
if(isset($_GET['id'])) {
$ID= 'id';
$childId=$_GET['id'];
$rowId=$_GET['id'];
$chartsql = "SELECT `feis_entered`, `competition_level1`, `dance_name1`, `firstpl_score1`, `2ndpl_score1`, `3rdpl_score1` FROM `mark_cards1` WHERE id = '$rowId'";
$chartres = mysqli_query($con,$chartsql);
$chartrow=mysqli_fetch_array($chartres);
if($chartres){
$compName = '.$chartrow["feis_entered"].';
$compLvl = '.$chartrow["competition_level1"].';
$danceName = '.$chartrow["dance_name1"].';
$first = '.$chartrow["firstpl_score1"].';
$second = '.$chartrow["2ndpl_score1"].';
$third = '.$chartrow["3rdpl_score1"].';
}
}
?>
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Ranking');
data.addColumn('number', 'Score');
data.addRows([
['1st Place', <?php echo $first;?>],
['2nd Place', <?php echo $second;?>],
['3rd Place', <?php echo $third;?>]
]);
var data = google.visualization.arrayToDataTable([
['Element', 'Score', { role: 'style' }],
[ '1st Place', <?php echo $first;?>, 'color: #91b224',],
[ '2nd Place', <?php echo $second;?>, 'color: #91b224',],
[ '3rd Place', <?php echo $third;?>, 'color: #91b224',],
]);
// Set chart options
var options = {title:'<?php echo $compName - $compLvl - $danceName;?>',
colors: ['#91b224'],
is3D:true,
width:600,
height:550};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
first place, second place, and third place are the fields. CompName, compLvl, and danceName are the title.
EDIT picture of source code below
the chart values should be numbers instead of strings...
try removing the quotes...
from...
$first = '.$chartrow["firstpl_score1"].';
$second = '.$chartrow["2ndpl_score1"].';
$third = '.$chartrow["3rdpl_score1"].';
to...
$first = $chartrow["firstpl_score1"];
$second = $chartrow["2ndpl_score1"];
$third = $chartrow["3rdpl_score1"];

Multi line Google Line Chart, using data from mySQL db

I'm going through a bit of a learning process, in order to create a small database backed reporting system for my company.
The intent is to draw a multi line chart using Google Charts, based on a mysql database.
I've managed to get the data to echo from the mysql database, but it's not generating the chart. All I get is the echo, and a blank space where the chart should be. The echo is shown for debugging purposes.
Here is the code :
<?php include 'confile.php';
$qry = "SELECT time,p1,p2,p3,p4 from $db WHERE date = '2016-03-02' ORDER BY time ASC";
$result = $conn->query($qry);
if($result === FALSE) {
echo mysql_errno($result) .": ". mysql_error($result) ."/n";
die(mysql_error());
}
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Time', 'type' => 'datetime'),
array('label' => 'Probe 1', 'type' => 'number'),
array('label' => 'Probe 2', 'type' => 'number'),
array('label' => 'Probe 3', 'type' => 'number'),
array('label' => 'Probe 4', 'type' => 'number')
);
while($r = mysqli_fetch_assoc($result)) {
$temp = array();
$temp[] = array($r['time']);
$temp[] = array($r['p1']);
$temp[] = array($r['p2']);
$temp[] = array($r['p3']);
$temp[] = array($r['p4']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></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.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?$jsonTable?>);
var options = {
title: 'Recorded Temperatures',
legend: {position: 'bottom' },
width: 800,
height: 600
};
var chart = new google.visualization.Table(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>
And this is the 'echo' output
{"cols":[{"label":"Time","type":"datetime"},{"label":"Probe 1","type":"number"},{"label":"Probe 2","type":"number"},{"label":"Probe 3","type":"number"},{"label":"Probe 4","type":"number"}],"rows":[{"c":[["03:02:07"],["270.26"],["298.40"],["111.54"],["228.06"]]},{"c":[["03:28:42"],["273.23"],["190.43"],["245.69"],["283.21"]]},{"c":[["07:26:04"],["144.33"],["217.26"],["206.53"],["167.68"]]},{"c":[["12:13:20"],["153.15"],["277.23"],["167.20"],["240.88"]]}]}
This is test data, using a test query on the db. Once I understand the formatting to render the chart, it will be setup to allow the user to select which date to view, etc.
This was the closest existing question I can find, but doesn't seem to answer the question.
Not able to generate a Google Chart using MySQL table data as the data source
Following the answer of #MickMackusa, I managed to hack this together to get it to work, by ensuring the mysql/php array was output in a manner acceptable to Google Charts.
Thanks to #MickMacUSA for his assistance.
The final, working code, is below.
<?php include 'confile.php';
$qry = "SELECT time,p1,p2,p3,p4 from $db WHERE date = '2016-04-16' ORDER BY time ASC";
$result = $conn->query($qry);
if($result === FALSE) {
echo mysqli_errno($result) .": ". mysqli_error($result) ."/n";
die(mysqli_error());
}
$i = 0; //iteration counter - start at 0
$totalRows = mysqli_num_rows($result); // we need this to know when to change the output
$targetRows = $totalRows - 1; //row indies start from 0, not 1.
foreach ($result as $row){
$comTime = str_replace(":",",",$row['time']); // for each row, remove the : and put , in its place
if ($targetRows == $i) { // if the index is the same value as the target (ie, it's the last row)...
$temp = "[[".$comTime."],".($row['p1']).",".($row['p2']).",".($row['p3']).",".($row['p4'])."]". PHP_EOL;
} else {
$temp = "[[".$comTime."],".($row['p1']).",".($row['p2']).",".($row['p3']).",".($row['p4'])."],". PHP_EOL;
}
$i = $i + 1;
$rows[] = $temp;
}
$table = $rows;
$data = implode($table); //format the table as a single string, with line returns
//echo $i;
//echo $data;
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<div id="chart" style="width: 900px; height: 500px"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
data.addColumn('timeofday','Time');
data.addColumn('number','Probe 1');
data.addColumn('number','Probe 2');
data.addColumn('number','Probe 3');
data.addColumn('number','Probe 4');
data.addRows([
<?php echo $data; ?> //dump the result into here, as it's correctly formatted
]);
var options = {
title: 'Recorded Temperatures',
legend: { position: 'bottom' },
width: 900,
height: 500,
hAxis: { format: 'hh:mm:ss' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(data, options);
}
</script>
</body>
</html>
Your number values must be formatted differently and you want timeofday not datetime.
According to: https://developers.google.com/chart/interactive/docs/reference#dataparam
Format your data to look like this:
{cols:
[
{"label":"Time","type":"timeofday"},
{"label":"Probe 1","type":"number"},
{"label":"Probe 2","type":"number"},
{"label":"Probe 3","type":"number"},
{"label":"Probe 4","type":"number"}
],
rows:
[
{c:[{v:[03,02,07],f:'03:02:07'},{v:270.26},{v:298.40},{v:111.54},{v:228.06}]},
{c:[{v:[03,28,42],f:'03:28:42'},{v:273.23},{v:190.43},{v:245.69},{v:283.21}]},
{c:[{v:[07,26,04],f:'07:26:04'},{v:144.33},{v:217.26},{v:206.53},{v:167.68}]},
{c:[{v:[12,13,20],f:'12:13:20'},{v:153.15},{v:277.23},{v:167.20},{v:240.88}]}
]
}
And you must echo it in the javascript:
change:
<?$jsonTable?>
to:
<?php echo $jsonTable; ?>
And put your javascript code block just before your </body> tag.
This is the full working code using the above data format that I tested on my server:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable(
{cols:[
{"label":"Time","type":"timeofday"},
{"label":"Probe 1","type":"number"},
{"label":"Probe 2","type":"number"},
{"label":"Probe 3","type":"number"},
{"label":"Probe 4","type":"number"}
],
rows:[
{c:[{v:[03,02,07],f:'03:02:07'},{v:270.26},{v:298.40},{v:111.54},{v:228.06}]},
{c:[{v:[03,28,42],f:'03:28:42'},{v:273.23},{v:190.43},{v:245.69},{v:283.21}]},
{c:[{v:[07,26,04],f:'07:26:04'},{v:144.33},{v:217.26},{v:206.53},{v:167.68}]},
{c:[{v:[12,13,20],f:'12:13:20'},{v:153.15},{v:277.23},{v:167.20},{v:240.88}]}
]
});
var options = {
title: 'Recorded Temperatures',
legend: { position: 'bottom' },
width: 900,
height: 500,
hAxis: { format: 'hh:mm:ss' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</body>
</html>
This is an alternative format that will be simpler/clearer/easier to build/comprehend using your mysqli results:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
data.addColumn('timeofday','Time');
data.addColumn('number','Probe 1');
data.addColumn('number','Probe 2');
data.addColumn('number','Probe 3');
data.addColumn('number','Probe 4');
data.addRows([
[[03,02,07],270.26,298.40,111.54,228.06],
[[03,28,42],273.23,190.43,245.69,283.21],
[[07,26,04],144.33,217.26,206.53,167.68],
[[12,13,20],153.15,277.23,167.20,240.88]
]);
var options = {
title: 'Recorded Temperatures',
legend: { position: 'bottom' },
width: 900,
height: 500,
hAxis: { format: 'hh:mm:ss' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</body>
</html>
See the SO Demo provided by WhiteHat:
google.charts.load('current', {
callback: drawChart,
packages: ['corechart', 'table']
});
function drawChart() {
var data = new google.visualization.DataTable({cols: [
{"label":"Time","type":"timeofday"},
{"label":"Probe 1","type":"number"},
{"label":"Probe 2","type":"number"},
{"label":"Probe 3","type":"number"},
{"label":"Probe 4","type":"number"}
],
rows: [
{c:[{v:[03,02,07],f:'03:02:07'},{v:270.26},{v:298.40},{v:111.54},{v:228.06}]},
{c:[{v:[03,28,42],f:'03:28:42'},{v:273.23},{v:190.43},{v:245.69},{v:283.21}]},
{c:[{v:[07,26,04],f:'07:26:04'},{v:144.33},{v:217.26},{v:206.53},{v:167.68}]},
{c:[{v:[12,13,20],f:'12:13:20'},{v:153.15},{v:277.23},{v:167.20},{v:240.88}]}
]
});
var table = new google.visualization.Table(document.getElementById('chart_0'));
table.draw(data);
var options = {
title: 'Recorded Temperatures',
legend: {position: 'bottom' },
width: 800,
height: 600,
hAxis: {
format: 'hh:mm:ss'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_1'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_0"></div>
<div id="chart_1"></div>

Google chart returns error-Uncaught ReferenceError: mon is not defined

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>

how to generate line chart in website

I like to generate line chart on my site ..
the data will change every hour so the chart should generate chart occur ding to the data
i inspired line chart in below site
http://www.nseindia.com/
so please somebody help me
Thanks
I'd recommend Raphael.js and it's charting plugin gRaphael
I recommend pChart, you can create pretty awesome charts with it. Pure PHP, nothing else.
I recommend Google Chart Tools, easy to generate the syntax and they look good!
Here is a very simple PHP function which generates nice Line charts, it uses Google Charts API, which is free:
function GenerateLineAreaChartHtmlCode($valuesArray, $values_count, $title, $hAxisLabels, $yUnit, $xUnit, $bk_color, $b_reverse_sort = false)
{
if (count($valuesArray) == 0)
return "";
$chart_function_name_id = rand(100, 100000);
$chart_html_code = "<script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script>
<script type=\"text/javascript\">
google.load(\"visualization\", \"1\", {packages:[\"corechart\"]});
google.setOnLoadCallback(drawChart$chart_function_name_id);
function drawChart$chart_function_name_id() {
var data = new google.visualization.DataTable();
data.addColumn('string', '$xUnit');
data.addColumn('number', '$yUnit');
data.addRows([";
if ($b_reverse_sort)
krsort($valuesArray, SORT_NUMERIC);
else
ksort($valuesArray, SORT_NUMERIC);
if ($values_count == 0)
$values_count = count($valuesArray);
for ($curPointN = 0; $curPointN <= $values_count; $curPointN ++)
{
$cur_point_value = $valuesArray[$curPointN];
if ($cur_point_value == "")
$cur_point_value = 0;
$chart_html_code .= "['$curPointN $xUnit', $cur_point_value],";
}
$chart_name = "chart_div" . rand(100, 100000);
$chart_html_code .= "]);
var chart = new google.visualization.AreaChart(document.getElementById('$chart_name'));
chart.draw(data, {width: 700, height: 300, title: '$title', backgroundColor: '$bk_color', fontName: 'Antic', fontSize: 12,
hAxis: {title: '$hAxisLabels', titleTextStyle: {color: '#FF0000'} },
vAxis: {}
});
}
</script><div id=\"$chart_name\"></div>";
return $chart_html_code;
}

Google Visualization Column Chart - How to make labels as currency

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

Categories