JSONp Datetime Javascript query fails on data.sparkfun iot - javascript

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) {

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

Making a simple 2 dimensional array

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
]);

c3.js - How can I set the y lines value to the first value from url (json data)

How can I set the y lines value to the first value from URL? (JSON data)
var chartDisplay = c3.generate({
bindto: '.chart',
data: {
url: '/stats',
mimeType: 'json',
},
grid: {
y: {
lines: [ {
value: data1 <---- this is what I cant figure out
}
]
}
}
});
The json data looks like this:
{
"data1": 3000,
"data2": [
3000,
3300.0,
3410.0,
4520.0,
]
}
try adding this to your chart declaration,
onrendered: function () {
this.api.ygrids([
{value: this.data.targets[0].values[0].value, text:'data 1 value'},
]);
},
this.api is basically the same as the 'chart' variable, and this.data is a pointer to the loaded dataset. targets[0] will be the first series loaded (data1) and values[0].value will be the value of the first entry
http://jsfiddle.net/y7axwubf/1/

How to plot a highstock single line series graph from ajax data

I have a rails app that fetches currency information data of the value of the sterling pound compared to the Kenyan shilling from a JSON API.
I want to use this data to plot a time-series graph of the value of the pound over a long period of time.
I'm using AJAX to populate data to a highcharts chart and my code is as follows:
<div id="currency", style="width: 220px, height:320px">
<script type="text/javascript">
$(document).ready(function(){
localhost = {}; //global namespace variable
localhost.currenctHTML = ""; //currency HTML built here
localhost.currencyValue = []; //array of percentage changes
localhost.currencyDate = []; //array of currency names
localhost.chart1 = {yAxisMin : null, yAxisMax : null};//obj holds things belonging to chart1
var url = '/forexes.json'
$.ajax({
url: url,
cache: false,
dataType: 'jsonp', //will set cache to false by default
context: localhost,
complete: function(data){
var a=JSON.parse(data.responseText);
// console.log(a);
var data_mapped = a.map(function (data){
return data.forex;
}).map(function (data) {
return {
currencyDate: data.published_at,
currencyValue: data.mean
}
});
this.currencyDate = _.pluck(data_mapped, 'currencyDate');
this.currencyValue = _.pluck(data_mapped, 'currencyValue');
console.log(this.currencyDate);
this.chart1.data.series[0].data = this.currencyValue;
this.chart1.data.xAxis.categories = this.currencyDate;
chart = new Highcharts.Chart(this.chart1.data);
}
});
localhost.chart1.data = { //js single-threaded, this obj created before callback function completed
chart: {
renderTo: "currency"
},
title: {
text: "Forex by Day"
},
xAxis: {
categories: null, //will be assigned array value during ajax callback
title: {
text: null
}
},
yAxis: {
title: {
text: "Pounds"
}
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat("%B %e, %Y", this.x) + ': ' +
"$" + Highcharts.numberFormat(this.y, 2);
}
},
series: [{
name: 'Pound',
data: null
}
]
};
});
</script>
</div>
**** returns
this.chart1.data.xAxis.categories = ["2003-01-01T00:00:00.000Z", "2003-01-02T00:00:00.000Z", "2003-01-03T00:00:00.000Z", "2003-01-04T00:00:00.000Z", "2003-01-05T00:00:00.000Z"]
this.chart1.data.series[0].data = [147.653, 148.007, 147.971, 148.202, 148.384, 147.888]
How do I use this data to generate a highstocks line chart resembling this
In the highstock you cannot use categories, only datetime type, so you should parse your data to timestamp and use it in the data.

Categories