I'm trying to display data from MSSQL. I saw an example at http://www.blueflame-software.com/blog/using-highcharts-with-php-and-mysql.
Value of Y Axis already good, but the X axis cannot display on my chart, so the value of chart only in 0 Xaxis,
data.php
mssql_select_db("CU-CAB01", $con);
$result = mssql_query("select count(nba) sumnba, datein from tbl_anggota where tgl_masuk > '2012-06-01'group by tgl_masuk");
while($row = mssql_fetch_array($result)) {
echo $row['tgl_masuk'] . "\t" . $row['jumlah']. "\n";
index.php
<script type="text/javascript" src="js/jquery-1.7.1.min.js" ></script>
<script type="text/javascript" src="js/highcharts.js" ></script>
<script type="text/javascript" src="js/themes/dark-blue.js"></script>
<script type="text/javascript">
var chart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Hourly Visits',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
type: 'datetime',
tickInterval: 10000 * 1000, // one hour
tickWidth: 0,
gridLineWidth: 1,
labels: {
align: 'center',
x: -3,
y: 20,
formatter: function() {
return Highcharts.dateFormat('%e', this.value);
}
}
},
yAxis: {
tickInterval: 2,
title: {
text: 'Anggota'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%l%p', this.x-(1000*3600)) +'-'+ Highcharts.dateFormat('%l%p', this.x) +': <b>'+ this.y + '</b>';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
name: 'Count'
}]
}
jQuery.get('data.php', null, function(tsv) {
var lines = [];
traffic = [];
try {
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
date = Date.parse(line[0] +' UTC');
traffic.push([
date,
parseInt(line[1].replace(',', ''),10)
]);
});
} catch (e) { }
options.series[0].data = traffic;
chart = new Highcharts.Chart(options);
});
});
</script>
and my data in tbl_anggota query result like this
sumnba datein
1 2012-07-03 00:00:00.000
4 2012-07-04 00:00:00.000
5 2012-07-05 00:00:00.000
5 2012-07-06 00:00:00.000
2 2012-07-16 00:00:00.000
5 2012-07-17 00:00:00.000
1 2012-07-18 00:00:00.000
2 2012-07-19 00:00:00.000
I think my mistake in parsing data with jquery on datein field, so my Xaxis only in null value..
Can someone get my chart to display the Xaxis value?
If you output query is like above, you have your X and Ys reversed in your parsing. The date field is after the count field:
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
date = Date.parse(line[1] +' UTC'); //your datin is after the '\t'
traffic.push([
date,
parseInt(line[0].replace(',', ''),10) //your count is before the '\t'
]);
});
And please, please fix the empty catch block. Ignore errors in a critical section of code is never a good idea.
Related
I'm trying to display average grades for each individual assignment but I'm getting no luck displaying it within a Highchart Column. It displays just the legend and "where the graph should be".
I have my div <div id="container"></div> as well as the necessary SQL code:
$row=$db->prepare ("SELECT r.due_date as Due, m.module_name as Module, r.ass_name as Assignment, avg(amount) as Grade
from score s
INNER JOIN assignment r ON s.assignment_id = r.ass_id
INNER JOIN module m ON r.module_id = m.module_id
WHERE r.module_id = 7
GROUP BY r.due_date asc;");
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Revenue vs. Overhead',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Amount'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
$.getJSON("avg_grades.json", function(json) {
options.xAxis.categories = json[0]['Assignments'];
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
});
});
</script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container"></div>
<?php
$db=new PDO('mysql:dbname=attendance_database;host=localhost;','user','password');
$row=$db->prepare ("SELECT r.due_date as Due, m.module_name as Module, r.ass_name as Assignment, avg(amount) as Grade
from score s
INNER JOIN assignment r ON s.assignment_id = r.ass_id
INNER JOIN module m ON r.module_id = m.module_id
WHERE r.module_id = 7
GROUP BY r.due_date asc;");
$row2=$db->prepare ("SELECT r.due_date as Due, m.module_name as Module, r.ass_name as Assignment, avg(amount) as Grade
from score s
INNER JOIN assignment r ON s.assignment_id = r.ass_id
INNER JOIN module m ON r.module_id = m.module_id
WHERE r.module_id = 7
GROUP BY r.due_date asc;");
$row3=$db->prepare ("SELECT r.due_date as Due, m.module_name as Module, r.ass_name as Assignment, avg(amount) as Grade
from score s
INNER JOIN assignment r ON s.assignment_id = r.ass_id
INNER JOIN module m ON r.module_id = m.module_id
WHERE r.module_id = 7
GROUP BY r.due_date asc;");
$row->execute();
###############################
$json_data=array();
$json_data['name'] = 'Assignments';
foreach($row as $rec)
{
$json_data['value'][]=$rec['Assignment'];
}
##########################
$json_data2=array();
$json_data2['name'] = 'Grade';
$row2->execute();
foreach($row2 as $rec2)
{
$json_data2['value'][]=$rec2['Grade'];
}
$result = array();
array_push($result,$json_data);
array_push($result,$json_data2);
$fp = fopen("avg_grades.json", "w");
fwrite($fp, json_encode($result));
fclose($fp);
echo json_encode($result);
?>
Expected outcome
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Monthly Average Rainfall'
},
subtitle: {
text: 'Source: WorldClimate.com'
},
xAxis: {
categories: [
'Find Hidden Data',
'Google Hacking',
'Caine Testing',
'Penetration Testing',
'FA 2'
],
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'Grades %'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} %</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Avg Grade',
data: [99, 70,80, 47.5, 70, 40]
}]
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
Actual outcome
Actual problem is in php $json_data2;
Instead of
$json_data2=array();
$json_data2['name'] = 'Grade';
$row2->execute();
foreach($row2 as $rec2)
{
$json_data2['value'][]=$rec2['Grade'];
}
it should be
$json_data2=array();
$json_data2['name'] = 'Grade';
$row2->execute();
foreach($row2 as $rec2)
{
$json_data2['value'][]=intval($rec2['Grade']); /*intval()*/
}
This will result in correct JSON string with array of numbers instead of array of string
final output [{"name":"Assignments","value":["Find Hidden Data","Google Hacking","Caine Testing","Penetration Testing","FA 2"]},{"name":"Grade","value":[99,70,80,47.5,70,40]}]
In your current JSON string,
this is demonstration to show when array of string ["99", "70","80", "47.5", "70", "40"] is converted to array of numbers [99, 70,80, 47.5, 70, 40] then only chart works as desired
var data = [{
"name": "Assignments",
"value": ["Find Hidden Data", "Google Hacking", "Caine Testing", "Penetration Testing", "FA 2"]
}, {
"name": "Grade",
"value": ["99", "70", "80", "47.5", "70", "40"]
}]
/*problem is here in second object value having array of string*/
var categories, datasN
for (var i = 0; i < data.length; i++) {
if (data[i].name == "Assignments") {
categories = data[i].value
}
if (data[i].name == "Grade") {
datasN = data[i].value.map(Number) /*converting string array to number array*/
}
}
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Monthly Average Rainfall'
},
subtitle: {
text: 'Source: WorldClimate.com'
},
xAxis: {
categories: categories,
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'Grades %'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} %</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Avg Grade',
data: datasN
}]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
Hope this gives you enough explanation
I try to use jqplot to plot a bar graph and I found a problem about first bar in graph, it isn't display point label. How to solve this problem? Thank you for help and suggestion.
Lohkaeo
I'm sorry, I forgot.
<script type="text/javascript">
$(document).ready(function() {
var s1 = [32100,0,0,990000,0,0,0,0,0,0,0,0];
var s2 = [36000,0,0,1800,0,4980,0,0,0,0,0,0];
var s3 = [0,0,0,0,0,0,0,0,0,0,0,0];
var ticks = ['1 2013','2 2013','3 2013','4 2013','5 2013','6 2013','7 2013','8 2013','9 2013','10 2013','11 2013','12 2013'];
$('#show-graph').css('height', '699px').jqplot([s1, s2, s3], {
title:'รายจ่าย',
seriesDefaults:{
renderer:$.jqplot.BarRenderer,
rendererOptions: {
barWidth: 20,
barMargin: 10
},
pointLabels: {
show: true,
formatString: "%#.2f",
hideZeros: true
}
},
axes:{
xaxis:{
renderer: $.jqplot.CategoryAxisRenderer,
tickRenderer: $.jqplot.CanvasAxisTickRenderer ,
tickOptions: {
fontFamily: 'Georgia',
fontSize: '10pt',
angle: -30,
labelPosition: 'middle'
},
ticks: ticks
},
yaxis: {
min: 0
}
},
legend: {
show: true,
location: 'ne',
placement: 'insideGrid'
},
series:[
{label: 'beverage'},
{label: 'equipment'},
{label: 'another'}
]
});
});
This is because the leftmost bar is too near to the edge so the jqPlot will not render that. Try to increase the width.
$jqplot('show-graph', [s1, s2, s3], {
title: 'xxxx',
width: 1000,
....
}
I get values to MySql database everyday at each hour.
I got site with highcharts, but I cant get it to work.
I need to get current day values from MySql organized to own hours.
Here is my Highcharts code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript">
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'chart',
defaultSeriesType: 'spline'
},
title: {
text: "Today's Values"
},
subtitle: {
text: 'Values by Hour'
},
credits: {
enabled: false
},
xAxis: {
categories: ['12AM', '1AM', '2AM', '3AM', '4AM', '5AM',
'6AM', '7AM', '8AM', '9AM', '10AM', '11AM','12PM', '1PM', '2PM', '3PM', '4PM', '5PM',
'6PM', '7PM', '8PM', '9PM', '10PM', '11PM']
},
yAxis: {
min: 0,
title: {
text: 'Values'
},
labels: {
formatter: function() {
return this.value
}
}
},
tooltip: {
valueDecimals: 2,
crosshairs: true,
shared: true,
formatter: function() {
return '$' + this.y;
}
},
plotOptions: {
spline: {
marker: {
radius: 4,
lineColor: '#666666',
lineWidth: 1
}
}
},
series: [{
name: 'Values',
data: [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
}]
});
});
</script>
Here is pic from MySql database how it looks like
chart
So, I need all values from MySql categorized to own hours at chart.
It should count values + show it at own category, any idea how to do this?
Im stuck with this beacause I dont know how to do this.
I advice to familiar with article about preprocessing data form MySQL http://docs.highcharts.com/#preprocessing-data-from-a-database
You should export your data from php as JSON, then if you would like you use categories for xAxis, you need to parse your JSON and push appropaite data to correct place.Similar with data points in series.
I am using the Highcharts JavaScript library to visualize some float values, which i feed into the js code via php. As you can see in the following picture, on each point's mouseover are now displayed the two values that correspond to the axes values and the text "text: undefined".
My question is: Is there a way to display a different text for each point of the scatter plot? I have a text that corresponds to each point, but I haven't found a way to display it.
My JavaScript/php code is:
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'scatter',
zoomType: 'xy'},
title: {
text: 'Average 24hrs Sentiment for <?php echo $channel?> by Gender '
},
subtitle: {
text: 'Source: '
},
xAxis: {
title: {
enabled: true,
text: 'Hours ([0-24h].[0-60mins])'
},
startOnTick: true,
endOnTick: true,
showLastLabel: true
},
yAxis: {
title: {
text: 'Sentiment (N. Bayes) %'
}
},
tooltip: {
formatter: function() {
return ''+
this.x +' hrs, '+ this.y +' sentiment, text: ';
}
},
legend: {
layout: 'vertical',
align: 'left',
verticalAlign: 'top',
x: 24,
y: 1,
floating: true,
backgroundColor: '#FFFFFF',
borderWidth: 1
},
plotOptions: {
scatter: {
marker: {
radius: 5,
states: {
hover: {
enabled: true,
lineColor: 'rgb(100,100,100)'
}
}
},
states: {
hover: {
marker: {
enabled: false
}
}
}
}
},
series: [{
name: 'Female',
color: 'rgba(223, 83, 83, .5)',
data: [
<?php
for($j=0;$j<$i1;$j++)
{
if($females[$j]['Hour'][0] == "0")
{
echo '['.$females[$j]['Hour'][1].'.'.$females[$j]['Min'].','.$females[$j]['Sent'].'"]';
}
else
echo '['.$females[$j]['Hour'].'.'.$females[$j]['Min'].','.$females[$j]['Sent'].'"]';
if(($j+1)!=$i1)
{
echo ",";
}
}
?>
]},
{
name: 'Male',
color: 'rgba(119, 152, 191, .5)',
data: [
<?php
for($j=0;$j<$i2;$j++)
{
if($males[$j]['Hour'][0] == "0")
{
echo '['.$males[$j]['Hour'][1].'.'.$males[$j]['Min'].','.$males[$j]['Sent'].',"'.$males[$j]['Text'].'"]';
}
else
echo '['.$males[$j]['Hour'].'.'.$males[$j]['Min'].','.$males[$j]['Sent'].',"'.$males[$j]['Text'].'"]';
if(($j+1)!=$i2)
{
echo ",";
}
}
?>
]}]
});
});
});
Thank you.
If the text is unique to each point, you can pass more than the x and y as values. In the following example I pass three other values: locked, unlocked, and potential. Then to access them in the tooltip formatter, do so by using the this.point.locked
this.x +' hrs, '+ this.y +' sentiment, text: ';
Try to set the text in this code line,
just in order to check whether my suggestion will solve your problem,
try :
this.x +' hrs, '+ this.y +' sentiment, text: '+this.x;
And then check whether (this.x) value appears insted of "undefined" .
First I want to say that I have looked at stackoverflow and highcharts forum, but have not been able to find a answer to my question, so I hope some kind soul can provide me with a working example of my problem.
I am trying to create a spline chart (not auto updating) from data in a mysql db created by rtg (rtg.sourceforge.net)
I am not a programmer, so please bear with me, for not creating clean/proper code (this includes copy/paste from several other sources).
There is 3 tables id (INT) , dtime (DATETIME) and counter (BIGINT) with the following sample:
1 2012-03-05 17:49:06 16991
2 2012-03-05 17:50:06 3774
3 2012-03-05 17:50:06 1272
(1,2,3 is the interface names)
I am trying to create with a chart that will show traffic for the last hour.
This is the content of my data.php
<?php
$con = mysql_connect("localhost","root","XXXXXXXX");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("rtg", $con);
$result = mysql_query("SELECT * FROM ifInOctets_1 ORDER BY dtime DESC LIMIT 0,60");
while($row = mysql_fetch_array($result)) {
echo $row['dtime'] . "\t" . $row['counter']. "\n";
}
mysql_close($con);
?>
The output from data.php is in the following format:
2012-03-05 20:53:31 245891 2012-03-05 20:53:31 8530 2012-03-05 20:53:31 6424577
rtg is polling 3 times pr min, so this results in 180 output "fields" from the above sql query.
This is the content of my index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Chart 1 Hour</title>
<script type="text/javascript" src="js/jquery-1.7.1.min.js" ></script>
<script type="text/javascript" src="js/highcharts.js" ></script>
<script type="text/javascript" src="js/themes/gray.js"></script>
<script type="text/javascript">
var chart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
marginRight: 130,
marginBottom: 25
},
credits: {
enabled: false
},
title: {
text: 'Bits',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
type: 'datetime',
tickInterval: 3600 * 1000, // one hour
tickWidth: 0,
gridLineWidth: 1,
labels: {
align: 'center',
x: -3,
y: 20,
formatter: function() {
return Highcharts.dateFormat('%Y%m%d%H%M%S', this.value);
}
}
},
yAxis: {
title: {
text: 'Bits'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%Y%m%d%H%M%S', this.x-(1000*3600)) +'-'+ Highcharts.dateFormat('%l%p', this.x) +': <b>'+ this.y + '</b>';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
name: 'BlaBla'
}]
}
// Load data asynchronously using jQuery. On success, add the data
// to the options and initiate the chart.
// This data is obtained by exporting a GA custom report to TSV.
// http://api.jquery.com/jQuery.get/
jQuery.get('data.php', null, function(tsv) {
var lines = [];
traffic = [];
try {
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
date = Date.parse(line[0] +' UTC');
traffic.push([
date,
parseInt(line[1].replace(',', ''), 10)
]);
});
} catch (e) { }
options.series[0].data = traffic;
chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<div id="container" style="width: 960px; height: 250px; margin: 0 auto"></div>
</body>
</html>
When I run the code it looks like all the data is cramped to the left side of the chart.
(Sorry could not post a screenshot, first time user.)
Since highcharts needs the the date + time in miliseconds, I have tried (among several other sql select statements) to change the Highcharts.dateFormat but without any luck.
Thanks in advance.
You need to convert your return date to return as the number of milliseconds since the epoch.
So SELECT * FROM ifInOctets_1 ORDER BY dtime DESC LIMIT 0,60 would become:
`SELECT UNIX_TIMESTAMP(dtime)*1000,counter FROM ifInOctets_1 ORDER BY dtime DESC LIMIT 0,60"
That way you have the correct timestamp in ms value that highcharts expects.