Dynamically changing Label in Line chart - javascript

I am getting the following JSON object from a webserver in response object:
(JSON Array :[{"JUL":"5"},{"AUG":"7"},{"SEP":"9"},{"OCT":"11"},{"NOV":"13"}, {"DEC":"15"},{"JAN":"17"},{"FEB":"19"},{"MAR":"21"},{"APR":"23"},{"MAY":"25"},{"JUN":"27"}])
I am taking keys of the JSON object in an array
var al_key = [];
//For loop for x axis dispaly.
alert("al_key.length --------->"+al_key.length);
var jsonObj = []; //declare array
for (var i = 0; i < al_key.length; i++) {
jsonObj.push({value: i, text: al_key[i].value});
}
// Add axes
chart.addAxis("x", {min:1, max: 12 ,labels: jsonObj , fixLower: "major", microTicks: true, majorTickStep: 1});
chart.addAxis("y", { min: 0, max: 50, vertical: true, fixLower: "major", fixUpper: "major", includeZero: true });
However, it's not working the way I expect it to. Any suggestions as to where I am getting this wrong? Or alternative ways to display months on the x-axis dynamically? Thanks in advance for any help.
Pasted response as a question edit:
Actually i am getting JSONArray Object which contain single JSONObject which contains values like
//Server side coding..
JSONObject object=new JSONObject();
object.put("JAN":"17");
object.put("FEB":"19");
object.put("MAR":"21");
object.put("APR":"23");
object.put("MAY":"24");
object.put("JUN":"27");
JSONArray arrayObj=new JSONArray();
arrayObj.add(object);
On System.out.println(arrayObj); // our json appears like {"JAN":"17"},{"FEB":"19"},{"MAR":"21"},{"APR":"23"}, //{"MAY":"24"},{"JUN":"27"}];
On jsp:
//Call to the database to fetch the desired value
dojo.xhrGet( { url : "/POC/Action.do",
handleAs : "json",
sync: true,
load : function(response, ioArgs) {
alert("retrived response ------"+response);
for(var i in response)
for(var x in response[i])
output.push(response[i][x]);
alert("Get value to draw line chart---------------------->"+output);
},
error: function(response, ioArgs){
dojo.byId("grid").innerHTML = "An error occurred, with response: " + response;
return response;
},
handleAs: "json" });
the response object contain the return value (JSONArray object);
now this key is need to be displayed in the x axis of the chart. Do i need to again get the key and prepare the json object which is formed in the form said above by you..

In reply to your updated information:
Change the way you send the JSON (based on the limited info available,I am assuming is a Java servlet using the org.jon package)
JSONArray array = new JSONArray();
arrayObj.put (new JSONObject("{'month':'JAN', 'value':'17'}");
// and repeat for the rest of the data
You can use it then in your dojo chart as I wrote below (jsonObj3).
Original comment.
Check at the examples here, specially the part:
labels: [{value: 0, text: "zero"},
{value: 2, text: "two"},
{value: 4, text: "four"}
and add the two series
addSeries("Series A", [1, 2, 3, 4, 5], {stroke: {color: "red"}, fill: "lightpink"}).
addSeries("Series B", [5, 4, 3, 2, 1], {stroke: {color: "blue"}, fill: "lightblue"}).
For the series, the JSON might be
var months = ["JUL","AUG","SEP","OCT","NOV","DEC","JAN","FEB","MAR","APR","MAY","JUN"];
var jsonObj2 = [];
for (var i = 0; i < months.length ; i++) {
jsonObj2.push({value: i, text: months[i]});
}
If you want one single JSON object, try arranging it like this:
var data = [{month: "JUL", value:"5"},
{month: "AUG", value:"7"},
{month: "SEP", value:"9"},
{month: "OCT", value:"11"},
{month: "NOV", value:"13"},
{month: "DEC", value:"15"},
{month: "JAN", value:"17"},
{month: "FEB", value:"19"},
{month: "MAR", value:"21"},
{month: "APR", value:"23"},
{month: "MAY", value:"25"},
{month: "JUN", value:"27"}];
var jsonObj3 = [];
for (var i = 0; i < data.length ; i++) {
jsonObj3.push({value: i, text: data[i].month});
}

Related

JavaScripts unexpected value change after parsing to json

I'm trying generate gantt chart from json string and I have weird problem with parsing Json string to Json object.
i have variable myString with json string looking like that:
{"c": [{"v": "496"}, {"v": "Task name 1"}, {"v": "9, "}, {"v": "Date(2018,6, 19)"}, {"v": "Date(2018, 6, 21)"}, {"v": null}, {"v": 100}, {"v": null}]}
after using var jsonData = JSON.parse(myString); values:"Date(2018,6, 19)"and"Date(2018, 6, 21)" are changed to: "Date(2018,7, 19)" and "Date(2018, 7, 21)"
And i don't know what's wrong with my code.
My full code:
$.ajax({
type: "GET",
url: URL,
data: data,
contentType: "application/json; charset=utf-8",
success: function (response) {
console.log(response['chart_data']);
var jsonData = JSON.parse(response['chart_data']);
console.log(jsonData);
var chart_height=jsonData["rows"].length;
google.charts.load('current', {'packages': ['gantt']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(jsonData);
var options = {
width: document.getElementById("task_list").offsetWidth,
height:30*chart_height,
gantt: {
trackHeight: 30
}
};
var chart = new google.visualization.Gantt(document.getElementById('chart_div'));
chart.draw(data, options);
}
}
});
SOLUTION:
Thanks to user1531038 new Date() function was executed while parsing, and Date function counts months from 0 to 11.
It is working fine as expected as both Date(2018,6, 19) & Date(2018, 6, 21) are string :

Adding new list to existing java script object

I'm trying to populate the dataset for a barchart. I would like to add 'dataset' to existing barData1 object.
But I'm getting following error. What am I doing wrong here?
error: jquery-3.1.1.min.js:2 Uncaught TypeError: Cannot read property
'splice' of undefined
<script type="text/javascript">
var jsprojStatList = #Html.Raw(ViewBag.projStatList);
$(document).ready(function () {
var barData1 = {
labels: ["No. Of Line Items", "Line Items Ordered", "( % )", "Line Items to be Ordered", "( % )", "PO Generated", "PO Approved", "PO Waiting for Approval"]
};
//var obj = JSON.parse(barData1);
//var parse_obj = JSON.parse(barData1);
var i = 0;
for (var key in jsprojStatList) {
if (jsprojStatList.hasOwnProperty(key)) {
var val = jsprojStatList[key];
barData1['datasets'].splice(i, 0, {
"label": val.BudgetTypeTitle, "backgroundColor": "rgba(220, 220, 220, 0.5)", "rgba(220, 220, 220, 0.5)": "#fff"
, "data": [val.NoOfBudgetItems, val.NoOfBudgetItemsOrdered, val.NoOfBudgetItemsOrderedPercentage, val.NoOfBudgetItemsToBeOrdered
, val.NoOfBudgetItemsToBeOrderedPercentage, val.POGenerated, val.POApproved, (val.POGenerated - val.POApproved)]
});
i++;
};
};
//}
var barOptions1 = {
responsive: true
};
var ctx21 = document.getElementById("barChart1").getContext("2d");
new Chart(ctx21, { type: 'bar', data: barData1, options: barOptions1
});
</script>
You'll have to define barData1['datasets'] itself as an array before you can add values to it:
var barData1 = {
datasets: [], // populated below
labels: ["No. Of Line Items", "Line Items Ordered", "( % )", "Line Items to be Ordered", "( % )", "PO Generated", "PO Approved", "PO Waiting for Approval"]
};
.splice() won't/can't automatically create the array for you with the first use.
Side notes:
Since it doesn't appear you're using i for anything else, .push(value) can be used in place of .splice(i, 0, value). That'll let you discard var i = 0 and i++.
If jsprojStatList is an Array (guessing from List in its name), a for..in loop isn't usually appropriate with them.

Charts in Angular js with JSON Object

I am trying to implement chart representation in angular js.
http://jtblin.github.io/angular-chart.js/
I was able to implement simple charts but I have a below data to be represented. It is in JSON format. I need help on how to convert JSON to arrays to be represented as charts. Below is JSON
[{"value": {"DE":2,"NP":20,"BD":28,"TW":1},
"end_time":"2016-07-05T07:00:00+0000"},
{"value":{"DE":5,"NP":11,"BD":22,"BE":2,"FJ":2},
"end_time":"2016-07-06T07:00:00+0000"},
{"value":{"DE":5,"NP":24,"BD":29},
"end_time":"2016-07-07T07:00:00+0000"}]
I am trying to convert it to the format
$scope.labels = ["January", "February", "March", "April", "May", "June","July"];
$scope.series = ['Series A', 'Series B'];
$scope.data = [
[65, 59, 80, 81, 56, 55, 40],
[28, 48, 40, 19, 86, 27, 90]
];
I understand that I need to iterate over my JSON object and create arrays.
My question is I have different labels in each of the JSON object. How do I convert it create an array with all the labels in each of the value and still maintain the order of counts.Like below
$scope.labels = ["DE", "NP", "BD", "TW", "BE", "FJ"];
$scope.series = ["2016-07-05T07:00:00+0000","2016-07-06T07:00:00+0000","2016-07-07T07:00:00+0000"]
$scope.data = [ [2,20,28,1,0,0],
[5,11,22,0,2,2],
[5,24,29]
]
If this can be better achieved using different libraries or charts in angularjs please do suggest
Have you even attempted something? You didn't show any solution. Anyway, here's a possible implementation
var source = [
{"value": {"DE":2,"NP":20,"BD":28,"TW":1},
"end_time":"2016-07-05T07:00:00+0000"},
{"value":{"DE":5,"NP":11,"BD":22,"BE":2,"FJ":2},
"end_time":"2016-07-06T07:00:00+0000"},
{"value":{"DE":5,"NP":24,"BD":29},
"end_time":"2016-07-07T07:00:00+0000"}
]
var $scope = {};
$scope.labels = [];
$scope.data = [];
$scope.series = [];
source.forEach(function(item){
$scope.series.push(item.end_time)
var values = []
Object.keys(item.value).forEach(function(key) {
if ($scope.labels.indexOf(key) === -1) {
$scope.labels.push(key)
}
values.push(item.value[key])
})
$scope.data.push(values)
})
console.log($scope)

Javascript: Add array elements to another array

I need to split elements in array noted below into 2 separate arrays:
data and labels:
Example using below would look like this:
data: [9, 23, 1, 6]
labels: ['service-1', 'service-2', 'service-3', 'service-4']
Array[16]
. 0: Object
. data: 9
. labels: "service-1"
. __proto__: Object
. 1: Object
. data: 23
. labels: "service-2"
. __proto__: Object
. 2: Object
. data: 1
. labels: "service-3"
. __proto__: Object
. 3: Object
. data: 6
. labels: "service-4"
. __proto__: Object
I'm trying to keep this simple as possible as I've tried several different things that have not worked including reference in this post: add array elements to other,
Try this:
var dataLabels = [
{data: 9, label: "service-1"},
{data: 23, label: "service-2"},
{data: 1, label: "service-3"},
{data: 6, label: "service-4"}
];
var data = [];
var labels = [];
dataLabels.forEach(function(element) {
data.push(element.data);
labels.push(element.label);
});
Assuming your array has a JS object notation, I think this should work:
var data = [];
var labels = [];
for (var i= 0;i<16; i++){
data[i] = array[i].data;
labels[i] = array[i].labels;
}
This should do the trick. Although perhaps a loop will suffice.
var dataLabels = [
{
data: 9,
labels: "service-1"
}, {
data: 23,
labels: "service-2"
}
];
var data = dataLabels.map(function(element) {
return element.data;
});
var labels = dataLabels.map(function(element) {
return element.labels;
});

Parsing values from core-response in Polymer

I'm making a request for x and y values from a flax/python backend using Polymer and I can read the values in console for the XMLHttpResquest response, but now I need to convert the output into a set of discrete x and y values (so it can be read by C3.js - a framework sitting on top D3 for graphing).
Here's the code I'm using to get the XMLHttpResquest response:
<paper-button affirmative hover on-tap="{{addNewGraph}}">Submit</paper-button>
Polymer("add-graphItem",{
addNewGraph: function () {
var HeaderName = this.$.graphOptionsLoad.$.headerValue.selectedItem.label;
var FunctionName = this.$.graphFunctionsLoad.$.functionValue.selectedItem.label;
console.log("The options are " +HeaderName +" and " +FunctionName);
var params = {};
if (this.$.graphOptionsLoad.$.headerValue.selectedItem) {
params['DataHeader'] = this.$.graphOptionsLoad.$.headerValue.selectedItem.label;
}
if (this.$.graphFunctionsLoad.$.functionValue.selectedItem) {
params['FunctionName'] = this.$.graphFunctionsLoad.$.functionValue.selectedItem.label;
}
this.$.sendOptions.params = JSON.stringify(params);
var x = this.$.sendOptions.go();
// this.$.sendOptions.go();
console.log(x)
// var ajax = document.querySelector("sendOptions");
var results = [];
this.addEventListener("core-response",
function(e) {
console.log(x.response);
}
);
}
});
And here's an example of the output from console.log(x.response);:
{
"graph": [
{
"Header": "MakeModeChange"
},
{
"x": [
0.0,
131.35,
26971.3,
27044.75,
27351.4,
27404.483333333334,
27419.416666666668,
33128.96666666667,
33549.13333333333,
34049.48333333333,
77464.26666666666,
77609.71666666666,
174171.85,
259166.98333333334
]
},
{
"y": [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14
]
}
]
}
Ultimately I need the output to look something like:
['x', 0.0, 131.35, 26971.3, 27044.75, 27351.4, 27404.483333333334...],
['y', 1, 2, 3, 4, 5, 6]
Here's a quick and dirty way to do it - not recommended for large scale or if you don't fully trust the response values. Also, obvious, but if their api/data structures changes you're SOL.
xArr = JSON.parse(x.response).graph[1].x
xArr.unshift('x')
yArr = JSON.parse(y.response).graph[2].y
yArr.unshift('y')
You'll get both arrays you'll need, you can combine as needed

Categories