Adding another data series in plot - javascript

I currently have a PHP file which returns:
[[38,38],[38,113],[38,188],[38,263],[38,338],[38,413],[38,488],[113,38],[113,113],[113,188],[113,263],[113,338],[113,413],[113,488],[188,38],[188,113],[188,188],[188,263],[188,338],[188,413],[188,488],[263,38],[263,113],[263,188],[263,263],[263,338],[263,413],[263,488],[338,38],[338,113],[338,188],[338,263],[338,338],[338,413],[338,488],[413,38],[413,113],[413,188],[413,263],[413,338],[413,413],[413,488],[488,38],[488,113],[488,188],[488,263],[488,338],[488,413],[488,488],[75,75],[75,150],[75,225],[75,300],[75,375],[75,450],[150,75],[150,150],[150,225],[150,300],[150,375],[150,450],[225,75],[225,150],[225,225],[225,300],[225,375],[225,450],[300,75],[300,150],[300,225],[300,300],[300,375],[300,450],[375,75],[375,150],[375,225],[375,300],[375,375],[375,450],[450,75],[450,150],[450,225],[450,300],[450,375],[450,450]]
I use this in an AJAX call like
$.ajax({
url:'fetcher/allseedpositions.php',
async: false,
success:function(datasets){
seedPos = jQuery.parseJSON(datasets);
allNodePos = $.plot($("#allnodepositions"),[ seedPos ],optionsSeed);
}
})
to plot but now I want another series to be plotted also along with this, with different symbol.
I am confused on using JSON and I cannot add more properties.

You should be able to create a new array and push the next data set for display. http://jsfiddle.net/fZbVL/
var dataSet1 = [
[1,5],[4,7]
];
var dataSet2 = [
[1,2],[3,4]
];
var dataSet3 = [
[1,4],[4,6]
]
var data = []
data.push(dataSet1);
data.push(dataSet2);
data.push(dataSet3);
$.plot($("#placeholder"),
data);

Related

Convert json string with duplicate keys into javascript array

I feel like this should be simple but I can't get my head around it. I'm trying to use Google Charts to display some simple data, I've got this data in a json string in a format like.
var json1 = [{"email":"abc#xyz","noOfOrders":"223"},{"email":"bcd#xyz.com","noOfOrders":"12"},{"email":"cde#xyz.com","noOfOrders":"132"}]
and I'm trying to get that into Google charts which has to be formatted as such.
var data = google.visualization.arrayToDataTable([
['Customer', 'Number of Orders'],
['abc#xyz.com', 223],
['bcd#xyz.com', 12],
['cde#xyz.com', 123]
]);
I'm trying to achieve with this javascript.
You could iterate through the JSON data and build the array needed for the chart.
var json = JSON.parse( [{...}] ); //parse the json string first, converting it to an array
var opts = [['Customer', 'Number of Orders']]; //add the headers now
for (var i = 0; i < json.length; i++) {
opts[] = [ json[i].email, json[i].noOfOrders ];
}
var data = google.visualization.arrayToDataTable( data );

Morris.js unable to display ajax-returned data

I have the following code to show a file's downloads in the past 30 days:
All data comes from "ajax/downloads.php" by doing a simple query to my database.
var pastDays = 30; //this value shows how many days back to show statistics
$.ajax({
type: "POST",
cache: false,
url: "ajax/downloads.php",
dataType: "json",
data: "days="+pastDays,
success : function(res) {
var obj = [];
for(var x = 0; x <= pastDays; x++){
var currObj = res[x];
var objCombo = currObj.split("|");
var objItem = "{date: '"+objCombo[0]+"', downloads: '"+objCombo[1]+"'}";
objItem = JSON.stringify(eval("(" + objItem + ")"));
obj.push(objItem);
}
console.log(obj);
}
This is the ajax response (res) that I already get:
console.log(res);
["07Apr|1", "06Apr|3", "05Apr|12", "04Apr|11", "03Apr|0", "02Apr|0", "01Apr|6", "31Mar|0", "30Mar|7", "29Mar|16", "28Mar|5", "27Mar|5", "26Mar|12", "25Mar|9", "24Mar|4", "23Mar|10", "22Mar|16", "21Mar|2", "20Mar|19", "19Mar|22", "18Mar|10", "17Mar|11", "16Mar|10", "15Mar|19", "14Mar|0", "13Mar|4", "12Mar|14", "11Mar|5", "10Mar|26", "09Mar|7", "08Mar|5"]
The console output I get after push is:
console.log(obj);
["{"date":"07Apr","downloads":"1"}", "{"date":"06Apr","downloads":"3"}", "{"date":"05Apr","downloads":"12"}", "{"date":"04Apr","downloads":"11"}", "{"date":"03Apr","downloads":"0"}", "{"date":"02Apr","downloads":"0"}", "{"date":"01Apr","downloads":"6"}", "{"date":"31Mar","downloads":"0"}", "{"date":"30Mar","downloads":"7"}", "{"date":"29Mar","downloads":"16"}", "{"date":"28Mar","downloads":"5"}", "{"date":"27Mar","downloads":"5"}", "{"date":"26Mar","downloads":"12"}", "{"date":"25Mar","downloads":"9"}", "{"date":"24Mar","downloads":"4"}", "{"date":"23Mar","downloads":"10"}", "{"date":"22Mar","downloads":"16"}", "{"date":"21Mar","downloads":"2"}", "{"date":"20Mar","downloads":"19"}", "{"date":"19Mar","downloads":"22"}", "{"date":"18Mar","downloads":"10"}", "{"date":"17Mar","downloads":"11"}", "{"date":"16Mar","downloads":"10"}", "{"date":"15Mar","downloads":"19"}", "{"date":"14Mar","downloads":"0"}", "{"date":"13Mar","downloads":"4"}", "{"date":"12Mar","downloads":"14"}", "{"date":"11Mar","downloads":"5"}", "{"date":"10Mar","downloads":"26"}", "{"date":"09Mar","downloads":"7"}", "{"date":"08Mar","downloads":"5"}"]
However when I feed it to Morris.bar I get "undefined" values.
Morris.js works fine though if I specify "var obj" in my code by hand and omit the ajax:
var obj = [ {"date":"07Apr","downloads":"1"}, {"date":"06Apr","downloads":"3"}, {"date":"05Apr","downloads":"12"}, {"date":"04Apr","downloads":"11"}, {"date":"03Apr","downloads":"0"}, {"date":"02Apr","downloads":"0"}, {"date":"01Apr","downloads":"6"}, {"date":"31Mar","downloads":"0"}, {"date":"30Mar","downloads":"7"}, {"date":"29Mar","downloads":"16"}, {"date":"28Mar","downloads":"5"}, {"date":"27Mar","downloads":"5"}, {"date":"26Mar","downloads":"12"}, {"date":"25Mar","downloads":"9"}, {"date":"24Mar","downloads":"4"}, {"date":"23Mar","downloads":"10"}, {"date":"22Mar","downloads":"16"}, {"date":"21Mar","downloads":"2"}, {"date":"20Mar","downloads":"19"}, {"date":"19Mar","downloads":"22"}, {"date":"18Mar","downloads":"10"}, {"date":"17Mar","downloads":"11"}, {"date":"16Mar","downloads":"10"}, {"date":"15Mar","downloads":"19"}, {"date":"14Mar","downloads":"0"}, {"date":"13Mar","downloads":"4"}, {"date":"12Mar","downloads":"14"}, {"date":"11Mar","downloads":"5"}, {"date":"10Mar","downloads":"26"}, {"date":"09Mar","downloads":"7"}, {"date":"08Mar","downloads":"5"} ];
Notice the difference between the two arrays:
From ajax I get:
["{"date":"07Apr","downloads":"1"}", "{"date":"06Apr","downloads":"3"}", ...]
While the one that works is like that:
[ {"date":"07Apr","downloads":"1"}, {"date":"06Apr","downloads":"3"}, ...]
Finally, this is how I initiate Morris:
Morris.Bar({
element: 'bar-requests',
data: obj,
xkey: ['date'],
ykeys: ['downloads'],
labels: ['downloads']
});
Any ideas as to how I could feed my ajax returned data to Morris??
Maybe I did not express the question properly in the first place, and since I didn't get any answers, I thought to simplify it and post it as a new question (hope I did't violate any of the site rulez)... In any case, problem solved!!!
Here is the solution that worked for me:
answer by Touhid Alam

How do I parse this JSON to get the data I need?

I've been struggling with this and need some help.
This is a sample of the JSON that would be returned to me. I have it assigned to a variable called result, so I can test it in my code. I'm not sure how else to fake the JSON being returned to me.
https://dl.dropboxusercontent.com/u/10842024/JSON.js
The JSON consists of two different objects, Line and Line2, each made up of multiple path (polyline) features.
I'm trying to create a Polyline object and add each one to a map using the ESRI JavaScript API. Here is the documentation for the Polyline object:
https://developers.arcgis.com/javascript/jsapi/polyline-amd.html#polyline2
require(["esri/geometry/Polyline"], function(Polyline) {
var polylineJson = {
"paths":[[[-122.68,45.53], [-122.58,45.55],
[-122.57,45.58],[-122.53,45.6]]],
"spatialReference":{"wkid":4326}
};
var polyline = new Polyline(polylineJson);
});
The JSON I get returned fits what the Polyline object needs:
"features": [
{
"attributes": {
"OBJECTID": 2368
},
"geometry": {
"paths": [
[
[
-123.94500566712864,
45.27071700030354
],
[
-123.9449701393585,
45.27069704962526
],
[
-123.94494162013,
45.27067958572745
],
[
-123.94489725722464,
45.2706251239781
],
[
-123.94489153421517,
45.27054128625377
]
]
]
}
},
But how can I loop through each feature and insert the JSON into the Polyline object so that it's formatted correctly?
I know I'm missing something because I can't figure out how to do it.
Something in that order I guess...
for (var i in result.results)
{
var features = result.results[i].features;
for (var j in features)
{
console.log(features[j].attributes.OBJECTID); // print OBJECTID
var geometry = features[j].geometry.paths;
for (var k in geometry)
{
console.log(geometry[k]); // print paths, arrays of points
var points = geometry[k];
for (var l in points)
console.log(points[l]); // print points
}
}
}
http://jsfiddle.net/e0dxn8ze/2/ open JavaScript console to see what goes
Here's an untested solution I just wrote.
// Get the JSON string
json_string = whaterver_function_gets_you_the_json();
// Parse JSON into JS
polys = JSON.parse(json_string);
// Loop through polys and create Polyline
polys.features.forEach(function(el) {
new Polyline(el.geometry);
});
Edit: Sorry I didn't see the JSON.js link. This solution should still work, you'd just have to adjust which object property you're looping through. For instance: result.results[0].features.forEach(function(el){}); or if you need to also loop through all the results you can just nest forEachs.

how to use JSON Data in chart.js?

hi i have been trying to use data from MYSQL database and use them to create graphical chart with chart.js. i encoded data into JSON data( through a php file name data1.php), now i need to convert these Json data back to array using Jquery or javascript.. i dont have much knowledge about AJAX.. so could u help me out??
data1.php produces JSON data as
[{"company_name":"project A","present_worth":"81531.946062978"},{"company_name":"project B","present_worth":"67313.916593765"},{"company_name":"project c","present_worth":"92440.723376746"}]
i need value of present_worth in an array
this is the script used to create bargraph.. instead of custom data (for eg data : [65,59,90,81,56,55,40])given here i want an array here with JSON data.
<script type="text/javascript">
function bar(){
var barChartData = {
labels :["January","February","March","April","May","June","July"],datasets : [
{
fillColor : "rgba(220,280,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
data : [65,59,90,81,56,55,40]
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
data : [28,48,40,19,96,27,100]
}
]
};
var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Bar(barChartData);
}
</script>
I am not quite sure if you mean this:
var chartjsData = [];
for (var i = 0; i < json.length; i++) {
chartjsData.push(json[i].present_worth);
}
http://jsfiddle.net/rnX2Z/1/
Otherwise comment ;)
So this a JSON data example,
var data = '{"name":"tom","Second":"smith","age":"20","height":"180"}'
Create a Variable to Parse the data
var obj9 = JSON.parse(data);
Then make another Variable to store your specific data. (.age, this is relative to your data set, eg .name, .height)
var cat = obj9.age;
Then you can use the the variable cat in your graph data.
data : [cat9,randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
Hope that helps.
Find out more about JSON
http://www.w3schools.com/json/default.asp

Highcharts with multiple series from JSON

After reading and testing since few days (And already post here but with a wrong question) I really need you because I fail again and again...
My goal : having many series on same charts (and many charts in the future)
My data source : a mysql and a json output :
"[{"name":"Station 1","data":"1360191600,398.625"},{"name":"Station 1","data":"1360192500,398.625"},{"name":"Station 1","data":"1360193400,398.25"},{"name":"Station 1","data":"1360194300,397.375"},{"name":"Station 1","data":"1360195200,397.5"},{"name":"Station 1","data":"1360196100,397.5"},{"name":"Station 1","data":"1360199700,396.75"},{"name":"Station 1","data":"1360200600,397"}...
These data are an example because in normal time I have many station and some with only the timestamp data.
My big fail at this moment is to send these information to the series:[] option.
I have try some loops like this :
data=JSON.parse(data) ;
var series = [];
series.data = [];
$.each(data,function(i,ligne) {
var string = JSON.stringify(ligne);
var obj = $.parseJSON(string);
//var index_serie = obj.name.slice(0,1) ;
console.log(obj) ;
points=(obj.data) ;
series.name=obj.name ;
series.data.push(points) ;
}) ;
options.series.push(series) ;
console.log(options.series) ;
var chart = new Highcharts.Chart(options);
The options of the chart are defined before the ajax call.
I have try with a other format of json like ["name":"station1","data":"[1321654,10],[5465... but I have difficulties to add the [] in my sql quesry and the GROUP_CONCAT have some limitation (2014 character)
So help me to create a nice loop in order to render multiple series with their name etc
Thanks for your help...
Can't you change that "almost" JSON to "another" JSON? Maybe something like this:
[{
"name":'station 1',
"data": [ [360191600,398.625], [360191600,398.625], [360191600,398.625] ... [360191600,398.625] ]
}, {
"name":'station 2',
"data": [ [360191600,398.625], [360191600,398.625], [360191600,398.625] ... [360191600,398.625] ]
}]
If not, you have to add some parsing for your values, example:
data = JSON.parse(data);
var names = [];
$.each(data, function (i, ligne) {
var ind = names.indexOf(ligne.name),
splited = ligne.data.split(','),
x = parseFloat(splited[0]),
y = parseFloat(splited[1]);
if (ind == -1) {
/*series name spotted first time need to add new series */
ind = names.push(ligne.name) - 1;
options.series.push({
data: [],
name: ligne.name
});
}
if(!isNaN(x) && !isNaN(y)){
options.series[ind].data.push([x,y]);
}
});
And working jsfiddle: http://jsfiddle.net/3bQne/40/

Categories

Resources