FlotCharts / PHP / MySQL - Goin crazy with multiple axes and realtime - php

I'm trying to do a realtime Bar Chart. On left (Y axis) i have clients Name
and on bottom (X axis) i have a number (a count from mysql).
Simply i cant understand why wont go the redraw. I've been trying solving the problem alone and searching on google and here last 2 days without any success.
Here is the code:
`
<script>
var rawData = [<?php echo getDataLog(); ?>];
var dataSet = [{ label: "Numero di Allarmi", data: rawData, color: "#E8E800" }];
var ticks = [<?php echo getDataLogName(); ?>];
var options = {
series: {
bars: {
show: true
}
},
bars: {
align: "center",
barWidth: 0.5,
horizontal: true,
fillColor: { colors: [{ opacity: 0.5 }, { opacity: 1}] },
lineWidth: 1
},
xaxis: {
axisLabel: "Allarmi",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 10,
max: 2000,
tickColor: "#5E5E5E",
color: "black"
},
yaxis: {
axisLabel: "Clienti",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 3,
tickColor: "#5E5E5E",
ticks: ticks,
color: "black"
},
legend: {
noColumns: 0,
labelBoxBorderColor: "#858585",
position: "ne"
},
grid: {
hoverable: true,
borderWidth: 2,
backgroundColor: { colors: ["#171717", "#4F4F4F"] }
}
};
function updateGraph(){
var rawData = [<?php echo getDataLog(); ?>];
var dataSet = [{ label: "Numero di Allarmi", data: rawData, color: "#E8E800" }];
var ticks = [<?php echo getDataLogName(); ?>];
$.plot($("#flot-placeholder"), dataSet, options);
$("#flot-placeholder").UseTooltip();
}
var previousPoint = null, previousLabel = null;
$.fn.UseTooltip = function () {
$(this).bind("plothover", function (event, pos, item) {
if (item) {
if ((previousLabel != item.series.label) ||
(previousPoint != item.dataIndex)) {
previousPoint = item.dataIndex;
previousLabel = item.series.label;
$("#tooltip").remove();
var x = item.datapoint[0];
var y = item.datapoint[1];
var color = item.series.color;
//alert(color)
//console.log(item.series.xaxis.ticks[x].label);
showTooltip(item.pageX,
item.pageY,
color,
"<strong>" + item.series.label + "</strong><br>" + item.series.yaxis.ticks[y].label +
" : <strong>" +x+ "</strong> Allarmi");
}
} else {
$("#tooltip").remove();
previousPoint = null;
}
});
};
function showTooltip(x, y, color, contents) {
$('<div id="tooltip">' + contents + '</div>').css({
position: 'absolute',
display: 'none',
top: y - 10,
left: x + 10,
border: '2px solid ' + color,
padding: '3px',
'font-size': '9px',
'border-radius': '5px',
'background-color': '#fff',
'font-family': 'Verdana, Arial, Helvetica, Tahoma, sans-serif',
opacity: 0.9
}).appendTo("body").fadeIn(200);
}
setInterval(function(){
updateGraph();
console.log("a");
},1000)
</script>`
I really give up on try to understand why wont refresh the graph

Related

How to show values on pie or bar graph chart in php using chart.js

I want to show values on graphs. i search alot but could not find my solution.
Here is the code below:
<script>
var ctx = document.getElementById("barChart");
ctx.height = 100;
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: <?php echo json_encode($Division); ?>,
datasets: [{
label: 'Target',
data: <?php echo json_encode($TARGET_QTY); ?>,
//backgroundColor: "rgba(255, 159, 64, 0.2)",
backgroundColor: "rgb(231, 123, 126)",
borderColor: "rgb(219, 219, 219)",
borderWidth: 1
},
{
label: 'Actual',
data: <?php echo json_encode($DISPATCH_QTY); ?>,
backgroundColor: "rgb(0, 191, 255)",
borderColor: "rgb(252, 252, 252)",
borderWidth: 1
}
]
},
options: {
responsive: true,
tooltips: {
"enabled": false
},
scales: {
yAxes: [{
gridLines: {
display:false,
},
ticks: {
beginAtZero:true
}
}]
},
title: {
display: true,
// position:"bottom",
text: 'Target vs Actual Dispatch'
},
hover: {
// Overrides the global setting
mode: 'label'
},
animation: {
duration: 1,
onComplete: function () {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset, i)
{
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function (bar, index) {
var data = dataset.data[index];
ctx.fillText(data, bar._model.x, bar._model.y - 5);
});
});
}
},
/*legend: {
display: true,
// position : "bottom",
labels: {
fontColor: 'rgb(0, 0, 0)'
}
}*/
}
});
</script>
<div class="row">
<div class="col-md-12">
<div class="chart">
<canvas id="barChart" style="position: relative; height: 300px;"></canvas>
</div>
</div>
</div>
I search alot but could not show values in the bar graph. In this code value will be shown on the top of the graph but could not show on the bar. i want to show value on the bars of graph. either its a bar chart or pie chart. i use chart.js library. Please help me to get rid of this situation. Thanks in Advance.

Flot chart - Hide x-axis data value if no data found on line chart

I'm trying to hide the x-axis data label if no data is found. Please refer to the screenshot below. I want to show "0" or empty text instead of the date "01/01/1970".
How can I do that? My current code for flot chart is as below:
$.plot(elem, dataset1,
{
lines: { show: true, fill:true },
points: { show: true },
shadowSize: 0,
yaxis : {
show : true,
axisLabel : '<font style="color:#787878"><i>Total Views</i></font>',
position: 'left',
axisLabelPadding: 10,
tickDecimals: 0,
color: "#E0E0E0"
},
xaxis: {
mode: "time",
timeformat: "%d/%m/%Y",
minTickSize: [1, "day"],
color: "#E0E0E0",
axisLabel: '<font style="color:#787878">Date</font>',
axisLabelPadding: 20,
},
grid: {
hoverable: true,
borderWidth: 0
},
legend: { show: true, container: $('#legend-container'), noColumns: 1 },
tooltip: true,
tooltipOpts: {
content: function(label, xval, yval) {
var d = new Date(xval);
return label + ' (' + d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear() +') : ' + yval
},
shifts: {
x: 20,
y: 0
},
defaultTheme: false
},
colors: [ "#4682B4" ]
}
You can add the following to the axis options to only show the axis if there are data points in your data set:
xaxis: {
show: dataset1.length > 0
...

How to avoid Y axis negative values from google charts

How to avoid the negative values from google chart, I tried viewWindow: { min: 0,} in my Y axis, but still it showing negative values only.
please help some one please. Thanks in advance
<div class="timeline-item">
<div id="top_x_div" style="width: 100%; height: 300px;"></div>
</div>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawStacked);
function drawStacked() {
var data = new google.visualization.arrayToDataTable([
['Courses', 'Students'],
["Electronics", 2 ],
]);
var options = {
legend: { position: 'none' },
isStacked: true,
colors: ['green'],
bars: 'vertical', // Required for Material Bar Charts.
axes: {
x: {
0: { side: 'bottom', label: 'Percentage'} // Top x-axis.
}
},
axes: {
y: {
0: { side: 'bottom', label: 'Students'}, // Top x-axis.
/* viewWindow: {
min: 0,
},*/
}
},
vAxis: {
viewWindow: {
min: 0
}
},
bar: { groupWidth: "90%" }
};
var chart = new google.charts.Bar(document.getElementById('top_x_div'));
chart.draw(data, options);
};
</script>
You need to set the viewWindow on the vAxis option.
vAxis: {
viewWindow: {
min: 0
}
}
Source

Nothing displayed in Highchart Column

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

PHP Jquery Flot Cpu usage

how do I use it to best?
can be represented by jquery chart the CPU usage?
I thought of jquery Flot.
How do I let the graphics automatically update?
Hope you can give me tips.
greeting
My attempt, unfortunately he only chooses random values
processed area:
<?php
function get_server_cpu_usage(){
$load = sys_getloadavg();
return $load[0];
}
?>
<script>
$(function() {
var data1 = [];
var totalPoints = 300;
function GetData() {
data1.shift();
while (data1.length < totalPoints) {
var prev = data1.length > 0 ? data1[data1.length - 1] : 50;
var y = prev + <?=get_server_cpu_usage()?> * 10 - 5;
y = y < 0 ? 0 : (y > 100 ? 100 : y);
data1.push(y);
}
var result = [];
for (var i = 0; i < data1.length; ++i) {
result.push([i, data1[i]])
}
return result;
}
var updateInterval = 100;
var plot = $.plot($("#reatltime-chart #reatltime-chartContainer"), [
GetData()], {
series: {
lines: {
show: true,
fill: true
},
shadowSize: 0
},
yaxis: {
min: 0,
max: 100,
ticks: 10
},
xaxis: {
show: false
},
grid: {
hoverable: true,
clickable: true,
tickColor: "#f9f9f9",
borderWidth: 1,
borderColor: "#eeeeee"
},
colors: ["#79D1CF"],
tooltip: true,
tooltipOpts: {
defaultTheme: false
}
});
function update() {
plot.setData([GetData()]);
plot.draw();
setTimeout(update, updateInterval);
}
update();
});
</script>
i dont know how to do with jquery,but using php and css we can do this
(hope this is what you are asking)
<style>
.showbar {
width: 8px;
margin: 1px;
display: inline-block;
position: relative;
background-color: #aeaeae;
vertical-align: baseline;
}
</style>
<?php
$load = sys_getloadavg();//normally sometimes you'll get float points lessthan 1 so to show these values in bar just some value to make it positive so that you can see the bar
echo '<div style="height: '.($load[0]).
'em;" class="showbar"></div>'.($load[1]).
'<div style="height: '.($load[2]).
' class="showbar"></div>';
?>
sample output

Categories