How to use JSON data to populate a d3 chart (highcharts) - javascript

var units = {
title: 'override'
};
var optionsPie = {
chart: {
renderTo: 'existingOrNew-chart',
defaultSeriesType: 'pie'
},
title: {
text: 'new'
},
tooltip: {
formatter: function() {
return '<b>' + this.point.name + '</b>: ' + this.y + ' ' + units.title+Math.round(this.percentage*100)/100 + ' %';
}
},
credits: {
enabled: false
},
exporting: { enabled: false },
series: []
};
$(document).ready(function() {
$.get('csvFiles/ExistingNew.csv', function(data) {
var seriesPie = {
data: []
};
console.log(data);
console.log(obj.Sheet6);
var seriesPieItem = new Array();
var lines = data.split('\n');
console.log(lines);
$.each(lines, function(lineNo, line) {
var items = line.split(',');
if (lineNo == 0) {
$.each(items, function(itemNo, item)
{
if (itemNo == 0) optionsPie.title.text = item;
if (itemNo == items.length - 1) units.title = item;
});
}
else
{
seriesPieItem = new Array();
$.each(items, function(itemNo, item)
{
if (itemNo == 0)
{
seriesPieItem.push(item);
}
else
{
seriesPieItem.push(parseFloat(item));
}
});
seriesPie.data.push(seriesPieItem);
}
});
optionsPie.series.push(seriesPie);
var chart = new Highcharts.Chart(optionsPie);
});
});
<div class="row">
<div class="my-3 mx-auto">
<div class="card" style="position: relative; width: 60vw;">
<div class="card-title text-center">
<h4><b>Existing or New Customer</b></h4>
</div>
<div id="existingOrNew-chart"></div>
</div>
</div>
</div>
This d3 chart is from highcharts. I used a csv file's data to populate this chart.
And I have this json Data:
{
"Sheet6": [
{
"RowLabels": "Existing",
"CountOfClientName": 21
},
{
"RowLabels": "New",
"CountOfClientName": 28
}
]
}
Now I have included a new feature that is uploading an xlsx file. But first I have to convert the xlsx file data into json data and use that in the chart. I made the conversion and I got the Json data above .How can I use the "Sheet6" data in the chart. Instead of using the csv file data, is it possible to use the json data("Sheet6") in the chart?. Can you please help me. Thank You

Related

Is it possible to plot "live data" in R language?

We want to plot live data in this site https://www.highcharts.com/demo/live-data is it possible to plot it with Highcharter library in R language if not is there any another solution to do that with R language?
Here is JavaScript code:
var defaultData = 'https://demo-live-data.highcharts.com/time-data.csv';
var urlInput = document.getElementById('fetchURL');
var pollingCheckbox = document.getElementById('enablePolling');
var pollingInput = document.getElementById('pollingTime');
function createChart() {
Highcharts.chart('container', {
chart: {
type: 'spline'
},
title: {
text: 'Live Data'
},
accessibility: {
announceNewData: {
enabled: true,
minAnnounceInterval: 15000,
announcementFormatter: function (allSeries, newSeries, newPoint) {
if (newPoint) {
return 'New point added. Value: ' + newPoint.y;
}
return false;
}
}
},
data: {
csvURL: urlInput.value,
enablePolling: pollingCheckbox.checked === true,
dataRefreshRate: parseInt(pollingInput.value, 10)
}
});
if (pollingInput.value < 1 || !pollingInput.value) {
pollingInput.value = 1;
}
}
urlInput.value = defaultData;
// We recreate instead of using chart update to make sure the loaded CSV
// and such is completely gone.
pollingCheckbox.onchange = urlInput.onchange = pollingInput.onchange = createChart;
// Create the chart
createChart();

How to add one more column in jquery datatable which is not present in the json response

I'm using one api in which the response is coming in two columns but in one column there are many parameters, I need to decode one column and want to show in different columns.
Column name coming from api timestamp, dataFrame, I need to show in 3 columns timestamp, oil temperature and winding temperature. I need to add one more column in datatable to show the values in the datatable.
sample json data
[{
"timestamp": "2018-07-21T07:56:23.838Z",
"dataFrame": "HA=="
},
{
"timestamp": "2018-07-21T08:16:23.902Z",
"dataFrame": "HA=="
}
]
output
Expected Output
Timestamp, Oil Temp, winding temp in 3 separate columns
code
<script>
window.onload = getddata();
function getddata() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var Readings = JSON.parse(xmlhttp.responseText);
//jquery data table - start
$(document).ready(function () {
$('#example').DataTable({
columnDefs: [{
"targets": 1,
"render": function (data, type, row, meta) {
var hexvalue =base64toHEX(data);
var deviceid= hexToDec(hexvalue.substr(1,1));
var oil_temp= hexToDec(hexvalue.substr(2,2));
var winding_temp= hexToDec(hexvalue.substr(4,2));
return 'oil temp: ' + oil_temp + ', Winding Temp: ' + winding_temp + ' ;
}
},
{
"targets": 0,
"render": function (data, type, row, meta) {
var updDate= UtcToIst(data).toLocaleDateString();
var updTime= UtcToIst(data).toLocaleTimeString();
var updDateTime=updDate + ", " + updTime;
return updDateTime ;
}
}
}
],
data: Readings,
columns: [{
"data": "timestamp"
}, {
"data": "dataFrame"
}
]
});
});
//data table code -close
}
};
xmlhttp.open("GET", "https://.., true);
xmlhttp.setRequestHeader("Authorization", "Basic a2VybmV");
xmlhttp.setRequestHeader("Content-type", "Application/json");
xmlhttp.send();
}
</script>
It seems to me the code is a little bit overcomplicated. Why not just reuse dataFrame over multiple columns? Perhaps I misunderstand the question ...
var table = $('#example').DataTable({
data: sampleReadings,
columns: [
{ data: 'timestamp', title: 'timestamp',
render: function(data) {
return data
/* dont know what UtcToIst is
var updDate= UtcToIst(data).toLocaleDateString();
var updTime= UtcToIst(data).toLocaleTimeString();
var updDateTime=updDate + ", " + updTime;
return updDateTime ;
*/
}
},
{ data: 'dataFrame', title: 'deviceid',
render: function(data) {
var hexvalue = base64toHEX(data);
return hexToDec(hexvalue.substr(1,1));
}
},
{ data: 'dataFrame', title: 'Oil temp',
render: function(data) {
var hexvalue = base64toHEX(data);
return hexToDec(hexvalue.substr(2,2));
}
},
{ data: 'dataFrame', title: 'Winding temp',
render: function(data) {
var hexvalue = base64toHEX(data);
return hexToDec(hexvalue.substr(4,2));
}
},
//I guess there is more data hidden in dataFrame
//You can almost copy paste new columns here
]
})
If you have 10.000 records it would be a good idea to cache the output from base64toHEX.
demo -> http://jsfiddle.net/fn0yL361/
You can simply add a new column and render related value. Please update the data tables column.
https://datatables.net/reference/option/columns.name
{ columnDefs: [{
"targets": 2,
"name": "winding temp",
"render": function (data, type, row, meta) {
var hexvalue =base64toHEX(data);
var deviceid= hexToDec(hexvalue.substr(1,1));
var oil_temp= hexToDec(hexvalue.substr(2,2));
var winding_temp= hexToDec(hexvalue.substr(4,2));
return 'Winding Temp: ' + winding_temp ;
}
},{
"targets": 1,
"name": "Oil temp",
"render": function (data, type, row, meta) {
var hexvalue =base64toHEX(data);
var deviceid= hexToDec(hexvalue.substr(1,1));
var oil_temp= hexToDec(hexvalue.substr(2,2));
var winding_temp= hexToDec(hexvalue.substr(4,2));
return 'oil temp: ' + oil_temp ;
}
},
{
"targets": 0,
"name" : "Timestamp",
"render": function (data, type, row, meta) {
var updDate= UtcToIst(data).toLocaleDateString();
var updTime= UtcToIst(data).toLocaleTimeString();
var updDateTime=updDate + ", " + updTime;
return updDateTime ;
}
}
],
data: Readings,
columns: [{
"data": "timestamp"
}, {
"data": "dataFrame"
},
{
"data": "dataFrame"
}
]
Here is an example, because there are spaces in Name so need some extra code to get field:
var str = "{timestamp: 'xxx', dataFrame: 'Old Time: xx, winding Time: yyyy, Ambient Time: zzzz'}";
var objOrg = JSON.parse(str);
var newJSon = [{}];
foreach (var itm in objOrg)
{
var new3Fields = itm.dataFrame;
var arr = new3Fields.split(',')
var newItem = {};
newItem.timestamp = itm.timestamp;
newItem.OldTime = JSON.parse(arr[0]).['Old Time'];
newItem.WindingTime = JSON.parse(arr[1]).['winding Time'];
newItem.AmbientTime = JSON.parse(arr[2]).['Ambient Time'];
newJSon += newItem;
}
newJSon <--- This is a list with 4 columns

Passing data into chart using HTML and JavaScript

The following code is used to display a chart. The problem is the "data" is hard coded in. How can I change this so that the chart displays values which are displayed using:
<div id="name"> </div>
<div id="testscore"></div>
The above 2 div's contain dynamic values. I want to display these values in the chart.
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
// title:{
// text: "Olympic Medals of all Times (till 2012 Olympics)"
// },
animationEnabled: true,
legend: {
cursor:"pointer",
itemclick : function(e) {
if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
}
else {
e.dataSeries.visible = true;
}
chart.render();
}
},
axisY: {
title: "Time"
},
toolTip: {
shared: true,
content: function(e){
var str = '';
var total = 0 ;
var str3;
var str2 ;
for (var i = 0; i < e.entries.length; i++){
var str1 = "<span style= 'color:"+e.entries[i].dataSeries.color + "'> " + e.entries[i].dataSeries.name + "</span>: <strong>"+ e.entries[i].dataPoint.y + "</strong> <br/>" ;
total = e.entries[i].dataPoint.y + total;
str = str.concat(str1);
}
str2 = "<span style = 'color:DodgerBlue; '><strong>"+e.entries[0].dataPoint.label + "</strong></span><br/>";
str3 = "<span style = 'color:Tomato '>Total: </span><strong>" + total + "</strong><br/>";
return (str2.concat(str)).concat(str3);
}
},
data: [
{
type: "bar",
showInLegend: true,
name: "Black",
color: "#000000",
dataPoints: [
{ y: 0.18, label: "Name"},
{ y: 0.12, label: "Name 1"},
{ y: 0.59, label: "Name 2"},
{ y: 1.15, label: "Name 3"},
]
},
]
});
chart.render();
}
</script>
You can simply call
var data = document.getElementById('name').value;
var data2 = document.getElementById('testscore').value;
If it's a single value, it would work; otherwise, you need to do it this way:
var array = $('#your.id').data('stuff');
Here, "stuff" is nothing but
<div data-stuff="some data" ></div>
Or, create an array by:
var array = new Array();
and finally, store the data into the array.

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.

problem with highcharts series option

Hi i am having problem with my highcharts 'series' options. i initialized the chart options as below:
var options = {
chart: {
renderTo: 'chart',
defaultSeriesType: 'line',
},
title: {
text: 'Weight Monitor',
},
xAxis: {
title: {
text: 'Date Measurement'
},
categories: []
},
yAxis: {
title: {
text: 'Weight (in Lbs)'
}
},
series: []
};
I kept the categories: [] blank so that i can put the values in categories later. Same thing i did with my series options. I kept the data:[] as blank to fill it later. Now i wrote the code to fill the data.
var lines = [
[2011,150],
[2012,121],
$.each(lines, function(lineNo, line) {
var items = line.toString().split(",");
$.each (items, function(itemNo, item) {
if(itemNo == 0){
alert("itemNo: " + itemNo + " item: " + item);
options.xAxis.categories.push(item);
alert(options.xAxis.categories);
}
else {
var series = {
data: []
};
alert("itemNo: " + itemNo + " item: " + item);
options.series.data.push(parseFloat(item));
alert(options.series.data);
};
});
});
var chart = new Highcharts.Chart(options);
Now when i execute this code, my categories[] is getting values properly, but the execution gets stuck when it is at "options.series.data.push(parseFloat(item))". I am getting the proper value in the "alert("itemNo: " + itemNo + " item: " + item);". but just after that it hangs while pushing the item in series.data[]
any idea what is the problem. and i am running this javascript in php project so don't know if there is any issue because of the language. thanks
The problem is options.series.data.push(parseFloat(item)).
If you look at your options object, you can see that your series array is empty. You can ad series object in your options definition as follows -
series: [{
data: []
}]
Also the line
var series = {
data: []
};
is of no use.

Categories