PHP Jquery Flot Cpu usage - php

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

Related

ChartJS Line Chart Multi Color

Let's say I want to mark 8am and 9am points as Red color and the others as green. How do I do it?
`
echo '
<div style="width:800px" >
<canvas id="myChart"></canvas>
</div>
<script>
var xValues = ["'.$time.'"];
var yValues = ['.$avgpercent.'];
// var zValues = [22];
var barColors = ["red"];
new Chart("myChart", {
type: "line",
data: {
labels: xValues,
datasets: [{
label: "AvgPercent",
backgroundColor: barColors,
data: yValues,
borderColor: "rgb(75, 192, 192)",
backgroundColor:"lightgreen"
}]
},
options: {
responsive: true,
legend: {display: true},
plugins: {
title: {
display: true,
text: "'.$cpuname.' 24Hrs Report"
}
}
}
});
</script>';
`
Above is the code I've used. $avgPercent has the percentage data(yvalues) and $time is the xvalues
pointBackgroundColor: function(context) {
var index = context.dataIndex;
var value = context.dataset.data[index];
return value < 0 ? 'red' : // draw negative values in red
index % 2 ? 'blue' : // else, alternate values in blue and green
'green';
}

Line Chart using Chart js with time data

I am creating a line chart using chartJs by passing date at X-Axis and time (mm:ss) at Y-Axis. I am not sure how to use chartJs with time values.I tried different solutions from stack but none works in my case.
Here is json file
{"label":["08-Aug-2019","11-Aug-2019","22-Aug-2019","25-Aug-2019"],"time":["1:08","1:44","2:27","1:02"],"chart_data":"{\"label\":[\"08-Aug-2019\",\"11-Aug-2019\",\"22-Aug-2019\",\"25-Aug-2019\"],\"time\":[\"1:08\",\"1:44\",\"2:27\",\"1:02\"]}"}
Here is what i am trying to code
<div id="time_chart"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script>
<script>
let sData = JSON.parse('<?php echo $chart_data; ?>');
let time_ctx = $("#time-chart");
//Line Chart
var time_data = {
labels: sData.label,
datasets: [
{
label: sData.label,
data: sData.time
}
]
};
//options line chart
var time_options = {
responsive: true,
title: {
display: false
},
legend: {
display: false
},
scales: {
yAxes: [{
type: 'time',
time: {
parser: 'm:s',
unit: 'minute',
unitStepSize: 2,
min: '0:0',
max: '30:00',
displayFormats: {
'seconds': 'm.s'
}
},
ticks: {
callback: function(value, index, values) {
//Ticks reverse does not work with time axes so we have to revert in this callback
if (values[values.length - index] != undefined) {
return moment(values[values.length - index].value).format('m.s');
}
}
}
}]
}
};
var chart2 = new Chart(time_ctx, {
type: "line",
data: time_data,
options: time_options
});
</script>
This is what I am getting with this code:
Although I didn't manage to use a time axis for both the x- and y-axes, I managed to create a workaround with a timed x-axis and a linear y-axis.
I parse your time and return the time in seconds (integer). I use this value to display your time and change the format back to mm:ss.
I hope this is what you wanted. I'm not sure you want the axes this way (because in your code you use the y-axis as type "time").
PS: My first post, please feel free to tell me what I can improve.
JSFiddle: https://jsfiddle.net/5837nmyo/
JSBin: https://jsbin.com/yadixolica/1/edit?html,js,output
let sData = {}
sData.label = ["08-Aug-2019","11-Aug-2019","22-Aug-2019","25-Aug-2019"]
sData.time = ["1:08","1:44","2:27","1:02"]
let chartData = {}
chartData.label = sData.label
chartData.time = parseTimeToSeconds(sData.time)
function parseTimeToSeconds(times){
let regex = /(\d*):(\d{2})/gm
let parsedTime = []
for (let x = 0; x < times.length; x++) {
let match = regex.exec(times)
parsedTime.push(parseInt(match[1])*60 + parseInt(match[2]))
}
return parsedTime
}
let time_ctx = document.getElementById('time_chart');
let time_data = {
labels: chartData.label,
datasets: [{
label: chartData.label,
data: chartData.time
}]
};
let time_options = {
responsive: true,
title: {
display: false
},
legend: {
display: false
},
tooltips: {
callbacks: {
label: function(tooltipItem, data){
let value = parseInt(tooltipItem.value)
if (value%60 < 10)
return Math.floor(value/60) + ":" + 0 + value%60
else
return Math.floor(value/60) + ":" + value%60
}
}
},
scales: {
xAxes: [{
type: 'time'
}],
yAxes: [{
ticks: {
min: 0,
max: 1800,
stepSize: 120,
callback: function(value, index, values) {
if (value%60 < 10)
return Math.floor(value/60) + ":" + 0 + value%60
else
return Math.floor(value/60) + ":" + value%60
}
}
}]
}
};
let chart2 = new Chart(time_ctx, {
type: "line",
data: time_data,
options: time_options
});

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

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

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

javascript php mysql flot

I encountered a new problem regarding my x-axis. My intention was to output a x-axis which indicates the time, while the y axis indicates the power. I decided to use time[i] and using graph.push([time[i], power[i]). However,my graph remains empty. I did an alert to output function and this was the result I got:
({1:"14:36", 2:"14:39", 3:"14:42", 4:"14:45", 5:"14:48", 6:"14:51", 7:"14:54", 8:"14:57"})
It's in hour: mins. What should I change to obtain a time X-axis?
$(function () {
var graph = [];
var power = <?php echo json_encode($data);?>;
var time = <?php echo json_encode($times);?>;
var row = <?php echo json_encode($nrow);?>;
//alert(time.toSource());
for (var i = 1; i < row; i += 1) {
//var test = time[i];
//alert(test);
graph.push([time[i], power[i]]);
}
var plot = $.plot($("#placeholder"),
[ { data: graph, label: "Power" } ], {
series: {
lines: { show: true },
points: { show: true }
},
grid: { hoverable: true, clickable: true },
yaxis: { min: 0, max: 25 }
});
You have to convert time from hour:mins to number
for (var i = 1; i < row; i += 1) {
//var test = time[i];
//alert(test);
var hhmm = time[i].split(":");
var hh = parseInt(hhmm[0]);
var mm = parseInt(hhmm[1])/60;
var tt = hh + mm;
graph.push([tt, power[i]]);
}
EDIT ( Eugene Wong) :
//var options = {
// xaxis: { ticks:[[1,time[1]],[2,time[2]],[3,time[3]],[4,time[4]],[5,time[5]],[6,time[6]],[7,time[7]],[8,time[8]]]}
//};
//alert(options.toSource());
var plot = $.plot($("#placeholder"),
[ { data: graph, label: "Power" } ], {
series: {
lines: { show: true },
points: { show: true }
},
grid: { hoverable: true, clickable: true },
yaxis: { min: 0, max: 25 },
xaxis: { mode: "time", timeformat:"%hh:%mm" }
//xaxis: { ticks:[[1,time[1]],[2,time[2]],[3,time[3]],[4,time[4]],[5,time[5]],[6,time[6]],[7,time[7]],[8,time[8]]]}
});
EDIT(Diode):
Even though I have created time charts before, this time setting x-axis configuration didn't work. Anyway I have fixed this by adding a tick formatter function. See the code below. 'graph' is the sample data array I used.
var graph = [[14.5, 10], [16.45, 15], [18.45, 20]];
var plot = $.plot($("#placeholder"),
[ { data: graph, label: "Power" } ], {
series: {
lines: { show: true },
points: { show: true }
},
grid: { hoverable: true, clickable: true },
yaxis: { min: 0, max: 25 },
xaxis: {
min:14,
max:20,
tickSize:0.5,
tickFormatter: function(value){
var hours = Math.floor(value);
hours = (hours < 10)?"0"+hours:hours;
var minutes = (value - hours) * 60;
minutes = (minutes < 10)?"0"+minutes:minutes;
return hours + ":" + minutes;
}
}
});
Have PHP output a Javascript timestamp instead of the already formatted date/time. Just remember a few caveats about timestamps:
PHP timestamps are seconds, whereas javascript ones are milliseconds, so multiply by 1000
flot plots in UTC time, so you may need to convert your timestamp to UTC before outputting
There is a good example of time series data on the flot website.
Remember to specify xaxis: { mode: "time" } in your flot options.

Categories