Looping through data and passing it to a chart - javascript

I have an array of data that I'm using to plot a Line Chart. I'm using ApexCharts.
let testData = [
{
cell_id: 5833307,
datetime: ["2019-05-07 11:28:16.406795+03", "2019-05-07 11:28:38.764628+03", "2019-05-07 12:18:38.21369+03", "2019-05-07 12:33:47.889552+03", "2019-05-08 08:45:51.154047+03"],
rsrq: ["108", "108", "108", "108", "109"]
},
{
cell_id: 2656007,
datetime: ["2019-07-23 15:29:16.572813+03", "2019-07-23 15:29:16.71938+03", "2019-07-23 15:29:16.781606+03", "2019-07-23 15:29:50.375931+03", "2019-07-23 15:30:01.902013+03"],
rsrq: ["120", "119", "116", "134", "114"]
}
];
let datasetValue = [];
for( let x=0; x<testData.length; x++ )
{
datasetValue =
{
chart: {
height: 380,
width: "100%",
type: "line"
},
stroke: {
curve: 'smooth',
width: 1.5,
},
markers: {
size: 4,
},
legend: {
show: true,
position: 'top'
},
series: [
{
name: testData[x].cell_id,
data: testData[x].rsrq
}
],
xaxis: {
categories: testData[x].datetime,
title: {
text: "Date"
}
},
yaxis: {
title: {
text: "RSSI"
}
}
}
}
var chart = new ApexCharts(document.querySelector("#signal"), datasetValue);
chart.render();
<div id="signal"></div>
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
So I take my JSON array, loop it in a for loop to obtain my datasets. I define an array variable datasetValue which i assign the looped data and pass it to my chart instance: new ApexCharts(document.querySelector("#rssi-signal"), datasetValue);
What is happening is only the last array object is being passed meaning there's something I'm missing/not passing to get all my data.

Restructure the testData by grouping series and categories
let series = [];
let categories = [];
for (let x = 0; x < testData.length; x++) {
series.push({
name: testData[x].cell_id,
data: testData[x].rsrq
});
categories.concat(testData[x].datetime);
}
let testData = [{
cell_id: 5833307,
datetime: ["2019-05-07 11:28:16.406795+03", "2019-05-07 11:28:38.764628+03", "2019-05-07 12:18:38.21369+03", "2019-05-07 12:33:47.889552+03", "2019-05-08 08:45:51.154047+03"],
rsrq: ["108", "108", "108", "108", "109"]
},
{
cell_id: 2656007,
datetime: ["2019-07-23 15:29:16.572813+03", "2019-07-23 15:29:16.71938+03", "2019-07-23 15:29:16.781606+03", "2019-07-23 15:29:50.375931+03", "2019-07-23 15:30:01.902013+03"],
rsrq: ["120", "119", "116", "134", "114"]
}
];
let series = [];
let categories = [];
for (let x = 0; x < testData.length; x++) {
series.push({
name: testData[x].cell_id,
data: testData[x].rsrq
});
categories = categories.concat(testData[x].datetime);
}
var chart = new ApexCharts(document.querySelector("#signal"), {
chart: {
height: 380,
width: "100%",
type: "line"
},
stroke: {
curve: 'smooth',
width: 1.5,
},
markers: {
size: 4,
},
legend: {
show: true,
position: 'top'
},
series: series,
xaxis: {
categories: categories,
title: {
text: "Date"
}
},
yaxis: {
title: {
text: "RSSI"
}
}
});
chart.render();
<div id="signal"></div>
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>

Since you are declaring an array outside the forloop
let datasetValue = {
chart: {
height: 380,
width: "100%",
type: "line"
},
stroke: {
curve: 'smooth',
width: 1.5,
},
markers: {
size: 4,
},
legend: {
show: true,
position: 'top'
},
series: [],
xaxis: {
categories: [],
title: {
text: "Date"
}
},
yaxis: {
title: {
text: "RSSI"
}
}
};
Inside for loop you should do
datasetValue.series.push(
{
name: testData[x].cell_id,
data: testData[x].rsrq
});
datasetValue.xaxis.categories.push(testData[x].datetime);
You should push the value inside the array instead of reassigning it in each iteration

The first mistake you are trying to do is defining the "datasetValue" as an array variable.
datasetValue = yourdata; //wrong in case of pushing data into array
You are trying to assign an object to array variable that contains only last results due to looping and assignment.
Instead, use push method of array to push the data into an array.
datasetValue.push(yourdata); //correct way to push data to array
So, there is no use to define "datasetValue" as array.
To achieve your objective you can apply loop with following
var datasetValue;
var series = [];
var categories = [];
for(let x=0; x<testData.length;x++) {
series.push({
name: testData[x].cell_id,
data: testData[x].rsrq
});
categories.concat(testData[x].datetime);
}
datasetValue = {
chart: {
height: 380,
width: "100%",
type: "line"
},
stroke: {
curve: 'smooth',
width: 1.5,
},
markers: {
size: 4,
},
legend: {
show: true,
position: 'top'
},
series,
xaxis: {
categories,
title: {
text: "Date"
}
},
yaxis: {
title: {
text: "RSSI"
}
}
};
var chart = new ApexCharts(document.querySelector("#signal"), datasetValue);
chart.render();

I move your for loop after datasetValue definition to add only series to it, and also change xaxis
for( let x=0; x<testData.length; x++ )
{
datasetValue.series.push({
name: testData[x].cell_id,
data: testData[x].rsrq
})
}
let testData = [
{
cell_id: 5833307,
datetime: ["2019-05-07 11:28:16.406795+03", "2019-05-07 11:28:38.764628+03", "2019-05-07 12:18:38.21369+03", "2019-05-07 12:33:47.889552+03", "2019-05-08 08:45:51.154047+03"],
rsrq: ["108", "108", "108", "108", "109"]
},
{
cell_id: 2656007,
datetime: ["2019-07-23 15:29:16.572813+03", "2019-07-23 15:29:16.71938+03", "2019-07-23 15:29:16.781606+03", "2019-07-23 15:29:50.375931+03", "2019-07-23 15:30:01.902013+03"],
rsrq: ["120", "119", "116", "134", "114"]
}
];
let datasetValue =
{
chart: {
height: 380,
width: "100%",
type: "line"
},
stroke: {
curve: 'smooth',
width: 1.5,
},
markers: {
size: 4,
},
legend: {
show: true,
position: 'top'
},
series: [
],
xaxis: {
categories: testData[0].datetime,
title: {
text: "Date"
}
},
yaxis: {
title: {
text: "RSSI"
}
}
}
for( let x=0; x<testData.length; x++ )
{
datasetValue.series.push({
name: testData[x].cell_id,
data: testData[x].rsrq
})
}
var chart = new ApexCharts(document.querySelector("#signal"), datasetValue);
chart.render();
<div id="signal"></div>
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>

Related

Create Pie chart for each Json object

I have one Json with multiple array and foreach array I want to create Pie chart, but I don't know how to do it.
This is the array thet I have. And this is what I tried :
function Pie() {
$.getJSON("/Admin/Attivita/OreOggi", function (data) {
console.log(data);
var oreTecico = [];
var oreTecico = [];
var oreMalatia = [];
var oreStraordinario = [];
var oreInfortunio = [];
var oreFerie = [];
for (var i = 0; i < data.length; i++) {
nomeTecnico.push(data[i].nome);
oreTecico.push(data[i].odinario);
oreMalatia.push(data[i].malatia);
oreStraordinario.push(data[i].straordinario);
oreInfortunio.push(data[i].infortunio);
oreFerie.push(data[i].ferie);
};
// Build the chart
Highcharts.chart('zdravko', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Ore segnate oggi'
},
tooltip: {
pointFormat: '<b>{point.name}</b>: {point.y:.1f} h.'
},
accessibility: {
point: {
valueSuffix: '%'
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
name: nomeTecnico[0],
colorByPoint: true,
data: [{
name: '',
y:0,
sliced: true,
selected: true
}, {
name: 'Odinario',
y: oreTecico[0]
}, {
name: 'Malatia',
y: oreMalatia[0]
}, {
name: 'Straordinario',
y: oreStraordinario[0]
}, {
name: 'Infortunio',
y: oreInfortunio[0]
}, {
name: 'Ferie',
y: oreFerie[0]
}]
}]
});
});
}
It shows only the last "data". I want to make fo each array one pie. If i have 100 arrays I want 100 pies.
UPDATE:
I added this :
data.forEach(function (el) {
var chartData = [el.data1, el.data2];
var chartContainer = document.createElement('div');
document.getElementById('zdravko').append(chartContainer);
Highcharts.chart(chartContainer, {
series: [{
type: 'pie',
data: chartData
}]
});
});
The chartData is array of undefined objects.
Is it possible to make for or foreach inside Highcharts?
You need to use the Highcharts.chart method in a loop, for example:
var data = [{
data1: 12,
data2: 25
}, {
data1: 67,
data2: 11
}];
data.forEach(function(el) {
var chartData = [el.data1, el.data2];
var chartContainer = document.createElement('div');
document.getElementById('container').append(chartContainer);
Highcharts.chart(chartContainer, {
series: [{
type: 'pie',
data: chartData
}]
});
});
Live demo: http://jsfiddle.net/BlackLabel/x95pbw7j/
API Reference: https://api.highcharts.com/class-reference/Highcharts#.chart

Json data for apexcharts

I have some problems rendering some data from a JSON in my apexchart series.
Here is the example of my chart with the data that I want to be in my JSON, and i don't know how to write it.
var _seed = 42;
Math.random = function() {
_seed = _seed * 16807 % 2147483647;
return (_seed - 1) / 2147483646;
};
var options = {
series: [{
name: "Q",
data: [0, 4800, 9500, null],
},
{
name: "Q - 1",
data: [0, 6500, 12000, 16000]
},{
name: "Q Target",
data: [15500, 15500, 15500, 15500]
},
],
chart: {
height: 350,
type: 'line',
zoom: {
enabled: false
}
},
dataLabels: {
enabled: false
},
stroke: {
curve: 'straight'
},
title: {
text: 'Clicks',
align: 'left'
},
grid: {
row: {
colors: ['#f3f3f3', 'transparent'], // takes an array which will be repeated on columns
opacity: 0.5
},
},
xaxis: {
categories: [' ', 'Month1', 'Month2', 'Month3'],
}
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
#chart {
max-width: 450px;
margin: 35px auto;
}
<script src="https://cdn.jsdelivr.net/npm/promise-polyfill#8/dist/polyfill.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/eligrey-classlist-js-polyfill"></script>
<script src="https://cdn.jsdelivr.net/npm/findindex_polyfill_mdn"></script>
<script src="https://cdn.jsdelivr.net/npm/es6-promise#4/dist/es6-promise.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/es6-promise#4/dist/es6-promise.auto.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<div id="chart"></div>
If someone could give me a hint, is kindly appreciated.
The JSON looks like this , for retrieving data for the apexchart
{
"data_clicks":[
{
"name":"Q",
"data":[
{
"x":" ",
"y":0
},
{
"x":"Month1",
"y":2400
},
{
"x":"Month2",
"y":5200
},
{
"x":"Month3",
"y":null
}
]
},
{
"name":"Q - 1",
"data":[
{
"x":" ",
"y":0
},
{
"x":"Month1",
"y":1800
},
{
"x":"Month2",
"y":7150
},
{
"x":"Month3",
"y":10200
}
]
},
{
"name":"Q Target",
"data":[
{
"x":" ",
"y":11000
},
{
"x":"Month1",
"y":11000
},
{
"x":"Month2",
"y":11000
},
{
"x":"Month3",
"y":11000
}
]
}
],

Highcharts: How to display each column as a separate series?

I'm trying to display the data from my json.
My json file looks like this:
0: {OGS: "26", STRM: "1811", ACAD_CAREER: null, YEAR: "2018"}1: {OGS: "4144", STRM: "1801", ACAD_CAREER: null, YEAR: "2018"}2: {OGS: "3935", STRM: "1802", ACAD_CAREER: null, YEAR: "2018"}3: {OGS: "16", STRM: "1812", ACAD_CAREER: null, YEAR: "2018"}length: 4__proto__: Array(0)
And here's my code:
<script>
$(function () {
var categData = [];
var statusACountData = [];
var statusBCountData = [];
var dateVal=[];
var statusVal=[];
var countVal = [];
var jsonvar = [];
$.getJSON('http://localhost:37590/get_OGSDataPerTermYear/ORT/2018', function (jsonData) {
for(i=0;i<jsonData.length;i++){
dateVal[i]=jsonData[i].STRM;
// statusVal[i]=jsonData[i].status;
countVal[i]=jsonData[i].OGS;
}
// jsonData
console.log(jsonData);
console.log(countVal);
console.log(categData);
// $(function () {
Highcharts.chart('container', {
chart: {
type: 'column'
},
xAxis: {
categories: dateVal,
crosshair: true
},
series: [{
name: dateVal,
data: countVal
}]
});
// });
});
});
</script>
The column is not showing and the 4 data which is: 1801 1802 1803 and 1804 only appears in 1 series. I want to make them each series with different data which is OGS number.
To make it as you expect (each column is a separate series) you can follow this approach:
Prepare series and xAxis.categories arrays. Each series.data array should have an appropriate amount of null points before the one with real value. Something like that:
categories:
["1811", "1801", "1802", "1812"]
series:
[{
name: "cat - 0",
data: [2456]
}, {
name: "cat - 1",
data: [null, 4144]
}, {
name: "cat - 2",
data: [null, null, 3935]
}, {
name: "cat - 3",
data: [null, null, null, 2316]
}]
plotOptions.column.grouping should be disabled:
Highcharts.chart('container', {
chart: {
type: 'column'
},
xAxis: {
crosshair: true,
categories: categories
},
plotOptions: {
column: {
grouping: false
}
},
series: series
});
Demo:
https://jsfiddle.net/BlackLabel/ynqjftLk/
API reference:
https://api.highcharts.com/highcharts/plotOptions.column.grouping
enter image description hereYour data is not in right format. If you need to plot STRM is x axis , you will need to put them in a separate array and assign it to xAxis.
The yAxis also accepts an array of objects and the object need to have two keys like name & data where data is an array .
Also OGS values are in string , so adding a + before jsonData[i].OGS will convert it to number.
let jsonData = [{
OGS: "2456",
STRM: "1811",
ACAD_CAREER: null,
YEAR: "2018"
}, {
OGS: "4144",
STRM: "1801",
ACAD_CAREER: null,
YEAR: "2018"
}, {
OGS: "3935",
STRM: "1802",
ACAD_CAREER: null,
YEAR: "2018"
}, {
OGS: "2316",
STRM: "1812",
ACAD_CAREER: null,
YEAR: "2018"
}]
var categData = [];
var statusACountData = [];
var statusBCountData = [];
var dateVal = [];
var statusVal = [];
var countVal = [];
var jsonvar = [];
for (let i = 0; i < jsonData.length; i++) {
dateVal[i] = jsonData[i].STRM;
countVal.push({
name: 'someText',
data: [+jsonData[i].OGS]
})
}
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Some Text'
},
subtitle: {
text: 'someTExt'
},
xAxis: {
categories: dateVal,
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'OGS'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: countVal
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
can you guys check my code for drilldown? it only display 1 data series right after i clicked the column on the first chart,.
$.getJSON('http://localhost:37590/get_OGSDataPerTermYear/' + strCampus + "/" +
data[i].YEAR, function (jsonDataDrill) {
const datadrill = jsonDataDrill
console.log(jsonDataDrill);
for (d = 0; d < datadrill.length; d++) {
categories = datadrill[d].STRM
dataseries.push({
id: datadrill[d].YEAR,
name: +datadrill[d].STRM,
data: [{
y: +datadrill[d].OGS
}]
})
}
});

Simplify JavaScript array variable

I'm looking to simplify this code. Any way to it so? Spring MVC + Apex Charts
var d = /*[[${s0}]]*/ null`; <-- It is sent via the Spring Framework. Basically represents datetime(in millis) at `d[0]`, `d[3]`,... Temperature at `d[1]`, `d[4]`,... and Humidity at `d[2]`, `d[5]`,...
<script type="text/javascript" th:inline="javascript">
var d = /*[[${s0}]]*/ null;
var options = {
chart: {
type: 'area',
height: 300
},
series: [
{
name: 'Temperature',
data: [
[d[0], d[1]],
[d[3], d[4]],
[d[6], d[7]],
[d[9], d[10]],
[d[12], d[13]],
[d[15], d[16]],
[d[18], d[19]],
[d[21], d[22]],
[d[24], d[25]],
[d[27], d[28]],
[d[30], d[31]],
[d[33], d[34]],
[d[36], d[37]],
[d[39], d[40]],
[d[42], d[43]],
[d[45], d[46]],
[d[48], d[49]],
[d[51], d[52]],
[d[54], d[55]],
[d[57], d[58]],
[d[60], d[61]],
[d[63], d[64]],
[d[66], d[67]],
[d[69], d[70]]
]
},
{
name: "Humidity",
data: [
[d[0], d[2]],
[d[3], d[5]],
[d[6], d[8]],
[d[9], d[11]],
[d[12], d[14]],
[d[15], d[17]],
[d[18], d[20]],
[d[21], d[23]],
[d[24], d[26]],
[d[27], d[29]],
[d[30], d[32]],
[d[33], d[35]],
[d[36], d[38]],
[d[39], d[41]],
[d[42], d[44]],
[d[45], d[47]],
[d[48], d[50]],
[d[51], d[53]],
[d[54], d[56]],
[d[57], d[59]],
[d[60], d[62]],
[d[63], d[65]],
[d[66], d[68]],
[d[69], d[71]]
]
}
],
xaxis: {
type: 'datetime'
},
yaxis: [
{
axisTicks: {
show: true
},
axisBorder: {
show: true,
},
title: {
text: "Temperature"
}
}, {
min: 0,
max: 100,
opposite: true,
axisTicks: {
show: true
},
axisBorder: {
show: true,
},
title: {
text: "Humidity"
}
}
],
legend: {
position: 'top',
horizontalAlign: 'center'
},
tooltip: {
x: {
format: 'HH:mm dd/MM/yy'
},
}
}
var chart = new ApexCharts(document.querySelector("#chart0"), options);
chart.render();
</script>
I just need to simplify sending data via d[0], d[1] etc. Is there any kind of loop or anything else I can use?
You could take a function which takes the data and a pattern for the wanted elements and an offset for increment for the next row.
function mapByPattern(data, pattern, offset) {
var result = [], i = 0;
while (i < data.length) {
result.push(pattern.map(j => data[i + j]));
i += offset;
}
return result;
}
var data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
result = { series: [
{ name: 'Temperature', data: mapByPattern(data, [0, 1], 3) },
{ name: "Humidity", data: mapByPattern(data, [0, 2], 3) }
]};
console.log(result);
Thank You, Nina. Code code didn't work exactly as i wanted but was so helpful to fix my own. Thanks alot! Here's some fixed code :)
var data = /*[[${s0}]]*/ null;
function mapByPattern(data, pattern, offset) {
var result = [], i = 0;
while (i < data.length) {
result.push(pattern.map(j => data[i + j]));
i += offset;
}
return result;
}
var options = {
chart: {
type: 'area',
height: 300
},
series: [
{
name: 'Temperature',
data: mapByPattern(data, [0, 1], 3)
},
{
name: "Humidity",
data: mapByPattern(data, [0, 2], 3)
}
],
xaxis: {
type: 'datetime'
},
yaxis: [
{
axisTicks: {
show: true
},
axisBorder: {
show: true,
},
title: {
text: "Temperature"
}
}, {
min: 0,
max: 100,
opposite: true,
axisTicks: {
show: true
},
axisBorder: {
show: true,
},
title: {
text: "Humidity"
}
}
],
legend: {
position: 'top',
horizontalAlign: 'center'
},
tooltip: {
x: {
format: 'HH:mm dd/MM/yy'
},
}
}
var chart = new ApexCharts(document.querySelector("#chart0"), options);
chart.render();

Loop to create lines chart in canvasjs

I have an array Object:
total =
[
{
date: 5/12/2017,
count: 5,
type: A
},
{
date: 5/15/2017,
count: 15,
type: A
},
{
date: 5/12/2017,
count: 4,
type: B
},
{
date: 5/15/2017,
count: 5,
type: C
}..
]
I wondering how to loop them in a line chart using CanvasJS, each line presents each type, the x-axis presents date, the y-axis presents count
Here is what I have so far:
var chart = new CanvasJS.Chart("chartContainer",
{
title: {
text: "My Counts"
},
axisX: {
title: "Date",
},
axisY: {
title: "Count"
},
data: []
});
You can run a for loop over your array and store dataPoints in different variable to later use it in your chart.
var dps1 = [];
var dps2 = [];
var dps3 = [];
for(var i = 0; i < total.length; i++) {
if(total[i].type === "A") {
dps1.push({x: new Date(total[i].date), y: total[i].count});
} else if(total[i].type === "B") {
dps2.push({x: new Date(total[i].date), y: total[i].count});
} else if(total[i].type === "C") {
dps3.push({x: new Date(total[i].date), y: total[i].count});
}
}
Once you store you dataPoints, you'll need to use it in your chart.
data: [{
type: "line",
dataPoints: dps1
}, {
type: "line",
dataPoints: dps2
}, {
type: "line",
dataPoints: dps3
}]

Categories

Resources