how to generate line chart in website - php

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

Related

PHP + MySQL - Display empty entries in a Google bar chart

I'm trying to implement an import/export per month graph for my website using Google Charts API with a MySQL database. Everything is ok, but I'm looking for a way to show in my chart also the months without imports or exports. Could someone please help me? Here is a screenshot of my graph, as you can see some months missing
<div id="columnchart_material" style="width: 800px; height: 500px;"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var dati = google.visualization.arrayToDataTable([
['Month', 'Imports', 'Exports'],
<?php
$q = "SELECT month(date) AS month, SUM(imports) AS imports, SUM(exports) AS exports FROM table WHERE year(date)=2020 GROUP BY month(date)";
$res_q=mysqli_query($db,$q);
//fetch data
while ($row = mysqli_fetch_array($res_q)) {
$entry = "['".$row{'month'}."',".$row{'imports'}.",".$row{'exports'}."],";
echo $entry;
}
?>
]);
var options = {
chart: {
title: 'Imports and Exports',
subtitle: 'Bar chart',
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(dati, google.charts.Bar.convertOptions(options));
}
Consider the following:
<?php
$array = array(1,2,3,5,7,11);
for($i=1;$i<=12;$i++){
if(in_array($i,$array)){echo $i.' yes<br>';} else {echo $i.' no<br>';}
}
?>
You can use an additional array that holds your data and that contains all the months:
<?php
// prepare array with default 'empty' data
$entries = []
for ($m = 1; $m <= 12; $m++) {
$entries[$m] = '[]';
}
And then add the existing data to this array by overwriting the default values:
// fetch data
while ($row = mysqli_fetch_array($res_q)) {
$entries[$row['month']] = "['".$row{'month'}."',".$row{'imports'}.",".$row{'exports'}."]";
}
// output
echo implode(',', $entries);

Highcharts and php for a dynamic chart

I have been at this some time trying to get highcharts to chart some data returned by php. I have done many searches and nothing works. I can write the php to deliver the data however it needs to be but how do you get it to dynamically chart it?????
I can deliver it as:
[["1372875867","44.8782806"],["1372875885","46.2020226"]]
or
[[1372876686,44.0655823],[1372876693,43.3360596], etc ]
but how do I get the data from the php output into the dyname example they display?????
!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
Highcharts.setOptions({
global : {
useUTC : false
}
});
// Create the chart
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'container',
events : {
load : function() {
// set up the updating of the chart eachsecond
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(),
y = Math.round(Math.random() * 100);
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 0
},
title : {
text : 'Live random data'
},
exporting: {
enabled: false
},
series : [{
name : 'Random data',
data : (function() {
// generate an array of random data
var data = [], time = (new Date()).getTime(), i;
for( i = -999; i <= 0; i++) {
data.push([
time + i * 1000,
Math.round(Math.random() * 100)
]);
}
return data;
})()
}]
});
});
</script>
</head>
<body>
<script src="../../js/highstock.js"></script>
<script src="../../js/modules/exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>
my current php is:
<?php
// include("$_SERVER[DOCUMENT_ROOT]/config/config.php");
include("adodb5/adodb.inc.php");
$connection = new COM("ADODB.Connection") or die("Cannot start ADO");
$result_set = $connection->Execute("
SELECT tag, TIME, value
FROM picomp
WHERE TIME >= '*-3m' AND tag = 'xxx:xx_xxx.xxx'
");
$result_count = 0;
// $labels = array();
while (!$result_set->EOF) {
$pidate = date("U", strtotime($result_set->fields[1]) );
if ($result_count <> 0){
print ",";
}else{
print "[";
}
print "[".$pidate.",".$result_set->fields[2]."]";
// array_push("{$result_set->fields[2]}");
$result_count = $result_count +1;
$result_set->MoveNext();
// echo "testing";
}
print "];";
You can use HighchartsPHP which is a wrapper for Highcharts, which basically allows you to write all that JS code in PHP. It's very useful and pretty simple to use.
HighchartsPHP on GitHub
Your timestamp should be multiplied by 1000, and both values should be numbers.
Please familair with soultion, how to prepare JSON, because you only print "as JSON", but it is not.
Take look at http://php.net/manual/en/function.json-encode.php where some examples are introduced.

Google Geo Chart

I'm using Google's Geo Charts API, and using json to update the data.
This is my map js (map.php):
google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var jsonData = $.ajax({
url: "includes/_ajax_home_map.php?metric=Clicks",
dataType:"json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
var options = {
//region: '009',
backgroundColor: 'EAF7FE',
colorAxis: {colors: ['910101']}
};
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data, options);
};
This is my php generated json (_ajax_home_map.php):
$data = '{
"cols": [
{"id":"","label":"Country","pattern":"","type":"string"},
{"id":"","label":"Popularity","pattern":"","type":"number"}
],
"rows": [';
$metric = $_REQUEST['roi_tag'];
$sql = "SELECT SUM($metric) as '$metric',tag_1 FROM Dashboard_ClientsCampaigns_Today_HoH WHERE tag_1 != '' GROUP BY tag_1";
$sql = mysql_query($sql);
$count = 1;
while($row = mysql_fetch_array($sql)){
$tag_1 = strtoupper($row["tag_1"]);
if($tag_1 == "UK")$tag_1 = "GB";
if($count != 1)$data .= ",";
$count++;
$data .= '{"c":[{"v":"'.$tag_1.'","f":null},{"v":'.$row[$metric].',"f":null}]}';
}
$data .= ']}';
echo $data;
Now when I connect these 2, I just get a blank map. No data is in there. BUT..here comes the strange part. If I browse directly to my PHP JSON, I get this:
{ "cols": [ {"id":"","label":"Country","pattern":"","type":"string"}, {"id":"","label":"Popularity","pattern":"","type":"number"} ], "rows": [{"c":[{"v":"AU","f":null},{"v":139,"f":null}]},{"c":[{"v":"CZ","f":null},{"v":3,"f":null}]},{"c":[{"v":"DE","f":null},{"v":4,"f":null}]},{"c":[{"v":"DK","f":null},{"v":978,"f":null}]},{"c":[{"v":"ES","f":null},{"v":32,"f":null}]},{"c":[{"v":"HU","f":null},{"v":2,"f":null}]},{"c":[{"v":"IE","f":null},{"v":65,"f":null}]},{"c":[{"v":"IT","f":null},{"v":5081,"f":null}]},{"c":[{"v":"PT","f":null},{"v":4452,"f":null}]},{"c":[{"v":"RO","f":null},{"v":16,"f":null}]},{"c":[{"v":"RS","f":null},{"v":0,"f":null}]},{"c":[{"v":"RU","f":null},{"v":0,"f":null}]},{"c":[{"v":"SE","f":null},{"v":69,"f":null}]},{"c":[{"v":"GB","f":null},{"v":28123,"f":null}]}]}
If I take this outputted JSON, copy it, home it in it's own file (data2.php), then get my map js to access it, it populates the map perfectly.
How on earth can I have 2 pieces of identical JSON and only one work with Google Charts?
Maybe because you try to load the PHP with the wrong param
_ajax_home_map.php?metric=Clicks
but in the code you look for
$metric = $_REQUEST['roi_tag'];
try
$metric = $_REQUEST['metric'];
..instead. And you are right by the way - the JSON works just fine! Thats not the problem.

How to include PHP in Javascript; Google Chart API

I am working with the google chart visualization API.
I have a variable in php:
`$value`
which contains the following:
['0',0, 0],['1',65, 35],['2',88, 35],['3',66, 35],['4',35, 35],['5',99, 100]
I want to use this $value below in data.addRows as follows however the output I am getting is blank
<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('string', 'Period');
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
data.addRows([
<?php echo $value ?>
]);
var options = {
width: 400, height: 240,
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
After some research it seems it is Ajax I am trying to attempt. Is this correct? Is there a simple way I can return the value $value to data.addRow??
Here is the process to which $value is set:
$i = "0";
$period = "0";
$chartrow = array();
$unitpriceNumR = 3
while ($i<3)
{
$chartrow[$i] = "['".$period."',".$sPrice[$i].", ".$uPrice[$i]."]";
$period++;
$i++;
}
switch ($currentStage)
{
case "0":
$value = $chartrow[0];
break;
case "1":
$value = $chartrow[0];
break;
case "2":
$value = $chartrow[0].",".$chartrow[1];
break;
}
In this example if $currentStage = "2" then $value is set to ['0',0, 0],['1',65, 35]
Ok now I have even tried a copy and paste of google code into my file and still no success of seeing a graph. (code taken from:http://code.google.com/intl/en-EN/apis/chart/interactive/docs/gallery/linechart.html)
<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('string', 'Year');
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
data.addRows([
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 860, 580],
['2007', 1030, 540]
]);
var options = {
width: 400, height: 240,
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
Using this code
$chartrow = array();
for ($i = 0; $i < 3; $i++ )
{
$chartrow[] = array((string) $i, $sPrice[$i], $uPrice[$i]);
echo $chartrow;
}
results in $chartrow displaying the word "Array" to the screen.
Please have a look at the JSON encode function provided with PHP. This will let you echo or print out a JSON encoded string that JavaScript transforms into a native object.
$value = array(
array('0', 0, 0),
array('1', 65, 35),
array('2', 88, 35),
...
);
...
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
// Change this and the following lines to:
data.addRows(<?php print json_encode($value); ?>);
EDIT
$i = 0;
$chartrow = array();
$unitpriceNumR = 3
for (; $i < 3; $i++ )
$chartrow[] = array((string) $i, $sPrice[$i], $uPrice[$i]);
switch ($currentStage) {
case "0":
case "1":
$value = $chartrow[0];
break;
case "2":
$value = array_slice($chartrow, 0, 2);
default:
// You should have some default value, seriously!!!
}
// Then go the json_encode way, it's safer and easier to maintain!
...
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
// Change this and the following lines to:
data.addRows(<?php print json_encode($value); ?>);
Change [<?php echo $value ?>] to <?php echo json_encode($value) ?>
echo $value produces Array(5) because PHP doesn't natively know how to represent an array as a string.
echo json_encode($value) produces:
[['0',0, 0],['1',65,35],['2',66,35],['4',35,35],['5',99, 100]]
so you don't need brackets around the <?php ... ?>.
http://php.net/manual/en/function.json-encode.php
EDIT: thanks for clarifying how the PHP variables are formed.
The problem is that you're manually converting arrays into strings, when you should let $json_encode do all of the work for you.
Revised version of the PHP code:
$chartrow = array();
$unitpriceNumR = 3;
for ($i=0; $i<=2; $i++)
$chart_row[$i] = array($i, $sPrice[$i], $uPrice[$i];
switch ($currentStage)
{
case '0':
case '1':
$value = $chartrow[0];
break;
case '2':
$value = array($chartrow[0], $chartrow[1]);
break;
}
EDIT2: I tried what you did (replacing the php block with what we expect the php block to produce) and it didn't work for me either. Firebug says 'Container is not defined' in Google's own code.
You forgot to add a div to your document. Add <div id='chart_div'></div> after the script.
So we're on the same page: http://jsfiddle.net/daemon/nnpeE/
Here is the answer to this problem
PHP: How to pass multiple variables to an array?
Whenever I have values like that I do this as my first script on the page and it seems to work for me. It also allows me to inspect what is going on with the PHP instead of the variable being hidden in some function. Note that this will create a global variable which might be not what you want.
<script>
var a = [<?php echo($var1) ?>];
</script>
EDIT:
I got your PHP code to work for me. The changes I made was I converted $i to just 0 not "0" The same goes for the switch statement . Also line 4 needs a semicolon after it. Then I put this
<script>
var a = [<?php echo($value) ?>];
</script>
And the output in the page was
<script>
var a = [['0',, ],['1',, ]];
</script>

How can i plot a google scatter chart using 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

Categories