Making a simple 2 dimensional array - javascript

I'm trying to create a real-time graph like this: http://www.flotcharts.org/flot/examples/ajax/index.html
The problem is that I need data like:
var rawData = [
[1325347200000, 60], [1328025600000, 100], [1330531200000, 15], [1333209600000, 50]
];
$(document).ready(function () {
var rx_bytes = [];
var iteration = 0;
//Options
var options = {
lines: {
show: true
},
points: {
show: true
},
xaxis: {
tickDecimals: 0,
tickSize: 1
}
};
//Initial Plot
$.plot("#networkStats", rx_bytes, options);
function getStatistics() {
iteration++;
$.ajax({
url: '/getStatistics',
type: 'post',
dataType: 'json',
success: function (statistics) {
console.log(statistics);
var network = statistics.networks.eth0;
rx_bytes.push({
index: iteration,
data: network.rx_bytes
});
console.log(rx_bytes);
//Plot
$.plot("#cpuStats", [rx_bytes], options);
//get data again
getStatistics();
}
});
}
getStatistics();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
And my array output is like this: http://prntscr.com/i3y8ve
How do I make an array like the one above?

This should solve it:
rx_bytes.push([
iteration,
network.rx_bytes
]);

Related

plotly.js page render is super slow with 10 charts in DOM. firefox freezes. whats wrong?

I am getting super slow page loads (~10s on chrome, ~15 using firefox) when rendering a page with 10 Plotly charts (lines and bars) with very few data points on each chart (<100 per chart).
I'm not getting any errors, and my js code runs in ~300ms without errors (i used console.log() with timestamps). there is no network activity whilst waiting for the charts to render.
Am I doing something wrong?
The charts are rendered using a loop which calls a function with different parameters:
ajax call:
$.ajax({
method: "GET",
url: '/app/api/dashboard/data',
success: function(payload){
console.log('starting bal hist')
var bal_hist = JSON.parse(payload.balance_history);
balanceHistoryChart(elementID='balanceHistory', data=bal_hist);
console.log('ending bal hist')
var data = JSON.parse(payload.aggregated);
data = data.map(function(object) {
object.value_date = new Date(object.value_date);
return object
})
var allCategories = data.map(x => x.category);
var categories = new Set(allCategories);
console.log('starting loop')
for (var category of categories){
var chartID = category.toLowerCase().replace(' ','_') + '_chart';
console.log('starting catChart')
catChart(elementID=chartID, category=category, data=data)
console.log('ending catChart')
}
console.log('end loop')
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
function that creates the plotly charts:
function catChart(elementID, category, data) {
let filterForCat = data.filter(obj => obj.category === category);
let dates = filterForCat.map(function(obj) {
return obj.value_date
});
let weeklyTotal = filterForCat.map(function(obj) {
return obj.weekly_total
});
let movingAv = filterForCat.map(function(obj) {
return obj.moving_av
});
var movingAvSeries = {
type: "scatter",
mode: "lines",
name: '4-week average',
x: dates,
y: movingAv,
line: {color: 'green'}
};
var weeklyTotalSeries = {
type: "bar",
name: 'weekly totals',
x: dates,
y: weeklyTotal,
line: {color: 'red'}
};
var layout = {
showlegend: false,
title: false,
margin: {
l: 30,
r: 20,
b: 20,
t: 20,
pad: 5
},
};
var data = [ movingAvSeries, weeklyTotalSeries ];
var config = {
responsive: true,
displayModeBar: false,
};

How can I plot Charts w/ time x axis from JSON and MySQL in Chart.JS?

I'd like to plot some charts using Chart.js.
I have a script that gets two arrays from a database in JSON format.
The two arrays are:
-An array of Temperature (float)
-An array of Time (Obtained by the Database at the moment in which a temperature enters it by means of the function Current_Timestamp ())
I'd like to be able to graph the temperatures depending on the date with Chart.js
$(document).ready(function(){
$.ajax({
url : "http://localhost/js/data.php",
type: "GET",
success : function(data) {
console.log(data);
var datos = {
VectorTemp : [],
VectorFecha : []
}
var len = data.length;
for (var i = 0; i<len;i++){
if (data[i].chipID == 1){
datos.VectorTemp.push(data[i].temp);
datos.VectorFecha.push(data[i].fecha);
}
}
console.log(datos);
var ctx = $("#line-chartcanvas");
var data = {
labels: [],
datasets: [
{
x: datos.VectorFecha[1],
y: datos.VectorTemp[1]
}
]
};
var options = {
responsive: true,
title: {
display: true,
text: "Chart.js Time Scale"
},
}
var chart = new Chart (ctx, {
type: "line",
data : data,
options: options
});
},
error: function(data) {
console.log(data);
},
});
});

JSONp Datetime Javascript query fails on data.sparkfun iot

been trying to select data from data.sparkfun based on when its posted. I want to display weather data from the currenttime and a day back.
The stream is at: LINK
I am no coder, just hacking my way through here.
One json line is like this:
[{
"humidity": "37.8919",
"hectopascals": "1017.7725",
"rainin": "0.0000",
"tempc": "21.3162",
"winddir": "-1",
"windspeedkmh": "0.0000",
"windgustkmh_10m": "0.0000",
"timestamp": "2017-02-25T15:11:08.581Z"
}]
The code I use is at: https://www.hanscees.com/photon/charts-data-sparkfun.html
function drawChart2() {
var public_key = 'yA0EjKV3owhKNx1NlN3w';
// JSONP request
var jsonData = $.ajax({
url: 'https://data.sparkfun.com/output/' + public_key + '.json',
//data: {page: 1}, see http://phant.io/docs/output/http/
// https://forum.sparkfun.com/viewtopic.php?f=44&t=40621
data: {
'gt': {
'timestamp': 'now - 2d'
}
},
dataType: 'jsonp',
}).done(function(results) {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time');
data.addColumn('number', 'TempC');
data.addColumn('number', 'Humidity');
$.each(results, function(i, row) {
data.addRow([
(new Date(row.timestamp)),
parseFloat(row.tempc),
parseFloat(row.humidity)
]);
}); // each row
// see https://google-developers.appspot.com/chart/interactive/docs/gallery/linechart#dual-y-charts
var materialOptions = {
chart: {
title: 'TempC, Humidity outside'
},
width: 550,
height: 500,
series: {
// Gives each series an axis name that matches the Y-axis below.
0: {
axis: 'TempC'
},
1: {
axis: 'Humid'
}
},
axes: {
// Adds labels to each axis; they don't have to match the axis names.
y: {
Pressure: {
label: 'TempC (Celsius)'
},
Humid: {
label: 'Humidity'
}
}
}
};
var materialChart = new google.charts.Line(ChartDivTemp);
materialChart.draw(data, materialOptions);
}); // results
} // jsondata
but the diagrams are either displaying all data in the json file (which makes it extremely slow), or when I use:
data: {page: 1},
it shows about 4 hours of data.
How can help to format the query correctly? This line:
data: {
'gt': {
'timestamp': 'now - 2d'
}
}
I did a post request thru Postman and it worked:
https://data.sparkfun.com/output/yA0EjKV3owhKNx1NlN3w.json?lt[timestamp]=now%20-2day
data: {
'lt': {
'timestamp': 'now - 2day'
}
}
So you code should work by adding 2day and changing gt to lt
This code does what I wanted:
// JSONP request
var jsonData = $.ajax({
url: 'https://data.sparkfun.com/output/' + public_key + '.json',
//data: {page: 1}, see http://phant.io/docs/output/http/
// https://forum.sparkfun.com/viewtopic.php?f=44&t=40621
data: {'gt': {'timestamp': 'now - 2day'}},
dataType: 'jsonp',
}).done(function (results) {

Javascript hard-coded object works as parameter, but not reference to global object

I'm running into an odd issue with JQuery Flot.
I had been running
var plot = null;
function initPlot () {
plot = $.plot("#graph", myData, { /* my options here */ });
}
and everything worked fine.
I moved my options data into a variable within the scope of the function
var plot = null;
function initPlot () {
var myOptions = { /* my options here */ };
plot = $.plot("#graph", myData, myOptions);
}
and again, everything works fine.
Then I moved the variable to a broader scope (so I could reference it in other functions).
var plot = null;
var myOptions = { /* my options here */ };
function initPlot () {
plot = $.plot("#graph", myData, myOptions);
}
Suddenly it won't plot correctly. What's even more confusing to me is that it gets the values of most of the options--the graph appears, just not the data.
Using Chrome's debugger, I can see that myOptions has the correct value at the time I call $.plot(). I also tried setting a local variable o = myOptions and calling $.plot() with o instead of myOptions, but this, too, fails to plot the data.
What's causing this and how do I fix it?
I should note that I'm using Flot.Grow and Flot.Stack, but disabling these does not change the result.
EDIT (again)
Per the comments, here is literally the state of my code:
<body>
<div id="graph" style="width: 100%; height: 800px;"></div>
<script>
var idMap = {};
var yesData = [];
var noData = [];
var incData = [];
var voteData = [{ label: "Yes votes", data: yesData },
{ label: "No votes", data: noData },
{ label: "Not met quorum", data: incData }];
var ticks = [];
var plot = null;
var myOptions = {
series: {
//stack: true,
lines: {
show: false,
fill: true,
steps: false,
},
bars: {
show: true,
barWidth: .8,
horizontal: true,
},
//grow: {
// active: false,
// steps: 20,
// stepDirection: "up",
// stepMode: "linear",
// valueIndex: 0,
// growings: [{
// valueIndex: 0,
// }]
//},
},
yaxis: {
min: -.2,
max: 10, //dictLen(idMap),
//ticks: ,
//tickLength: 0,
},
xaxis: {
min: 0,
max: 200,
},
grid: {
hoverable: true,
},
};
function dictLen(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
function setDataPoint(val) {
var total = val.r["yes"] + val.r["no"];
if (total < val.q) {
incData.push([total, idMap[val.id]]);
}
else {
yesData.push([val.r["yes"], idMap[val.id]]);
noData.push([val.r["no"], idMap[val.id]]);
}
}
function initData() {
$.getJSON('/Vote/results', function (data) {
$.each(data, function (key, val) {
idMap[val.id] = key;
ticks.push([key + .4, val.nm]);
setDataPoint(val);
});
initPlot();
});
}
function initPlot() {
plot = $.plot("#graph", voteData, myOptions);
}
$(document).ready(function () {
initData();
});
</script>
</body>
Turns out I'm a bit of an idiot.
The issue was that I was calculating myOptions.yaxis.max before idMap was populated. Then, while I was waiting for an answer here, I did some refactoring on the database side, which resulted in an empty dataset.
When I fixed the db and set myOptions to only static values, it worked fine.

JS for Loop in Flot with JSON Data

I am attempting to create a dynamic flot graph dependant upon the data given to it, my flot graph is using JSON for its information and here is an example of the dataset:
{
"total":[[1377691200,115130],[1377694800,137759],[1377698400,137759],[1377702000,137759],[1377705600,137759],[1377709200,139604],[1377712800,137759],[1377716400,137759],[1377720000,137759],[1377723600,137759],[1377727200,137759],[1377730800,138156],[1377734400,137759],[1377738000,137759],[1377741600,137759],[1377745200,137759],[1377748800,138156],[1377752400,137759],[1377756000,137759],[1377759600,168831],[1377763200,137759],[1377766800,0],[1377770400,0]],
"dev0":[[1377691200,115130],[1377694800,137759],[1377698400,137759],[1377702000,137759],[1377705600,137759],[1377709200,139604],[1377712800,137759],[1377716400,137759],[1377720000,137759],[1377723600,137759],[1377727200,137759],[1377730800,138156],[1377734400,137759],[1377738000,137759],[1377741600,137759],[1377745200,137759],[1377748800,138156],[1377752400,137759],[1377756000,137759],[1377759600,168831],[1377763200,137759],[1377766800,0],[1377770400,0]],
"dev1":[[1377691200,0],[1377694800,0],[1377698400,0],[1377702000,0],[1377705600,0],[1377709200,0],[1377712800,0],[1377716400,0],[1377720000,0],[1377723600,0],[1377727200,0],[1377730800,0],[1377734400,0],[1377738000,0],[1377741600,0],[1377745200,0],[1377748800,0], [1377752400,0],[1377756000,0],[1377759600,0],[1377763200,0],[1377766800,0],[1377770400,0]]
}
The script i have created already:
$(".bytes_portal_pop").click(function(e) {
e.preventDefault();
var graph=$(this).data('graph');
var range=$(this).data('range');
var divid=$(this).data('divid');
var title=$(this).data('boxtitle');
$.getJSON("/action/sites/GetFlotStats/?graph=" + graph + "&range=" + range, function(json) {
//succes - data loaded, now use plot:
var plotarea = $("#" + divid);
var dev0=json.dev0;
var dev1=json.dev1;
$.plot(
$("#" + divid),
[
{
data: dev0,
lines:{show: true, fill: true},
label: "dev0",
},
{
data: dev1,
lines:{show: true, fill: true},
label: "dev1",
},
],
{
xaxis: {mode:"time"},
grid: {hoverable: true},
tooltip: true,
tooltipOpts: {
content: "Traffic: %y GB"
}
}
);
});
$("#boxtitleB_flot").html(title);
});
This way works fine and displays the two lines as i need however i would like it to be dynamic i.e. so i dont have to define each graph line i believe todo this i simply need a for or each() loop on the
var dev0=json.dev0;
and
{
data: dev0,
lines:{show: true, fill: true},
label: "dev0",
},
Any help achieving this would be much appreciated.
Correct, just loop it and generate your series objects dynamically.
Given a json return like:
jsonObj = {
"total":[[1377691200,115130],[1377694800,137759],[1377698400,137759],[1377702000,137759],[1377705600,137759],[1377709200,139604],[1377712800,137759],[1377716400,137759],[1377720000,137759],[1377723600,137759],[1377727200,137759],[1377730800,138156],[1377734400,137759],[1377738000,137759],[1377741600,137759],[1377745200,137759],[1377748800,138156],[1377752400,137759],[1377756000,137759],[1377759600,168831],[1377763200,137759],[1377766800,0],[1377770400,0]],
"dev0":[[1377691200,115130],[1377694800,137759],[1377698400,137759],[1377702000,137759],[1377705600,137759],[1377709200,139604],[1377712800,137759],[1377716400,137759],[1377720000,137759],[1377723600,137759],[1377727200,137759],[1377730800,138156],[1377734400,137759],[1377738000,137759],[1377741600,137759],[1377745200,137759],[1377748800,138156],[1377752400,137759],[1377756000,137759],[1377759600,168831],[1377763200,137759],[1377766800,0],[1377770400,0]],
"dev1":[[1377691200,0],[1377694800,0],[1377698400,0],[1377702000,0],[1377705600,0],[1377709200,0],[1377712800,0],[1377716400,0],[1377720000,0],[1377723600,0],[1377727200,0],[1377730800,0],[1377734400,0],[1377738000,0],[1377741600,0],[1377745200,0],[1377748800,0], [1377752400,0],[1377756000,0],[1377759600,0],[1377763200,0],[1377766800,0],[1377770400,0]]
};
Create an array of series like:
var series = [];
$.each(jsonObj, function (key, val) {
var serie = {};
serie.label = key;
serie.data = val;
series.push(serie);
});
And then create the plot:
$.plot(
$("#placeholder"),
series,
{}
);
Fiddle here.

Categories