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

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

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

Looping through data and passing it to a chart

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>

Highcharts data value from variable array string

Got a column called ChartData in database with a string value of 4,11,25,36,50. Trying to assign this value to a hidden variable so JS can read the value of this and put this value in the data option using high charts. I have console.log the variable and looks like its appearing as a string rather than an array when being parsed across the server side to the client side.
C# code
string str = reader["ChartData"].ToString();
string[] strList = str.Split(','); //seperate the hobbies by comma
// convert it in json
dataStr = JsonConvert.SerializeObject(strList, Formatting.None);
hiddenvariable.Value = dataStr;
JS code:
function CreateBoxPlot() {
var hv = $('#hiddenvariable').val();
alert(hv); //["40","61","65","74","77"]
var chart;
var titleText = 'Test Chart Title';
var subTitleText = 'Test Chart Subtitle';
var type = 'boxplot';
var data = hv;
console.log(data); //["40","61","65","74","77"]
$(function () {
$('#container').highcharts({
chart: { type: type, inverted: true },
title: { text: titleText },
subtitle: { text: subTitleText },
legend: { enabled: false },
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
pointWidth: 50
}
},
xAxis: {
visible: false
},
yAxis: {
visible: true,
title: {
text: 'Values'
},
plotLines: [{
value: 80,
color: 'red',
width: 2
}]
}
});
chart = $('#container').highcharts();
chart.addSeries({ data: data });
});
}
However when i hardcode data to the below value this works. How do i format this correctly when its parsed over to the JS side:
var data = [[40,61,65,74,77]]
You have to convert the string '["40","61","65","74","77"]' to js array with numbers. To make it work on each browser you can follow this approach:
Parse the string to js array using JSON.parse()
Loop through the created array and convert each element to number:
var json = '["40","61","65","74","77"]',
dataString = JSON.parse(json),
data = [],
i;
for (i = 0; i < dataString.length; i++) {
data[i] = +dataString[i];
}
Code:
$(function() {
var json = '["40","61","65","74","77"]',
dataString = JSON.parse(json),
data = [],
i;
for (i = 0; i < dataString.length; i++) {
data[i] = +dataString[i];
}
$('#container').highcharts({
chart: {
inverted: true
},
legend: {
enabled: false
},
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
pointWidth: 50
}
},
xAxis: {
visible: false
},
yAxis: {
visible: true,
title: {
text: 'Values'
},
plotLines: [{
value: 80,
color: 'red',
width: 2
}]
}
});
chart = $('#container').highcharts();
chart.addSeries({
data: data
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container"></div>
Demo:
https://jsfiddle.net/BlackLabel/ay1xmgoc/
Taking reference from the comments, add this to your code and then try.
var data = hv.map(function (element) {
return +element;
});

Highcharts Using CSV instead of JSON

I tried the code like this with many small restructuration and modification but without success.
Here is the code:
$(function () {
$.get('data.csv', function(data) {
// split the data set into ohlc and volume
var ohlc = [],
volume = [],
dataLength = data.length,
// set the allowed units for data grouping
groupingUnits = [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]],
i = 0;
for (i; i < dataLength; i += 1) {
ohlc.push([
data[i][0], // the date
data[i][1], // open
data[i][2], // high
data[i][3], // low
data[i][4] // close
]);
volume.push([
data[i][0], // the date
data[i][5] // the volume
]);
}
$('#chart').highcharts({
rangeSelector: {
selected: 1
},
title: {
text: 'AAPL Historical'
},
yAxis: [{
labels: {
align: 'right',
x: -3
},
title: {
text: 'OHLC'
},
height: '60%',
lineWidth: 2
}, {
labels: {
align: 'right',
x: -3
},
title: {
text: 'Volume'
},
top: '65%',
height: '35%',
offset: 0,
lineWidth: 2
}],
data: {
csv: data
},
series: [{
type: 'candlestick',
name: 'AAPL',
data: ohlc,
dataGrouping: {
units: groupingUnits
}
}, {
type: 'column',
name: 'Volume',
data: volume,
yAxis: 1,
dataGrouping: {
units: groupingUnits
}
}]
});
});
});
Here is data.csv:
Date,Open,High,Low,Close,Volume
2013-12-20,9371.08,9413.09,9352.98,9400.18,161686900
2013-12-19,9279.68,9351.9,9257.24,9335.74,98276500
2013-12-18,9145.35,9190.73,9122.05,9181.75,82342700
2013-12-17,9142.75,9161.8,9085.12,9085.12,72207500
2013-12-16,9004.62,9187.78,8997.75,9163.56,99105600
2013-12-13,9016.78,9046.63,8990.58,9006.46,67761700
2013-12-12,9032.67,9060.54,8984.28,9017,75120200
2013-12-11,9093.26,9153.14,9065.51,9077.11,64845800
2013-12-10,9180.29,9223.73,9091.97,9114.44,74363400
Can you help me to figure out the problem or purpose new approch please ?
What is my goal ?
Is to be able to load a CSV file inside the chart instead of using JSON file.
Why ?
Because modifing CSV file is more easier for me using PHP than JSON, and it's for performance too.
Thank's
When you do data.length, you are getting length of the csv file string. What you need to do is split the data with the newline delimiter.
// sample from data
var data = `Date,Open,High,Low,Close,Volume
2013-12-20,9371.08,9413.09,9352.98,9400.18,161686900
2013-12-19,9279.68,9351.9,9257.24,9335.74,98276500`;
// split by \n (new line)
data = data.split('\n'); // now data is an array of rows
var finalObj = [];
// iterate over the rows
data.map(function(row){
var obj = {};
// row is a string separated by ','
row = row.split(','); // now row is an array
obj['date'] = row[0];
obj['open'] = row[1];
obj['high'] = row[2];
obj['low'] = row[3];
obj['close'] = row[4];
obj['volume'] = row[5];
finalObj.push(obj);
})
console.log(finalObj);
Output:
[
{
date:'Date',
open:'Open',
high:'High',
low:'Low',
close:'Close',
volume:'Volume'
},
{
date:'2013-12-20',
open:'9371.08',
high:'9413.09',
low:'9352.98',
close:'9400.18',
volume:'161686900'
},
{
date:'2013-12-19',
open:'9279.68',
high:'9351.9',
low:'9257.24',
close:'9335.74',
volume:'98276500'
}
]

Highcharts not showing string value

I'm trying to add localstorage values into highchart series but it doesn't work.
When i print the "newString" value on the console and replace the value for "newString" at the code it works but it doesn't when I use var newString.
Here is the code:
$(document).ready(function () {
var archive,
j = "",
keys = Object.keys(localStorage),
x = keys.length;
var i = 0;
while (i < x) {
archive = JSON.parse(localStorage.getItem(keys[i]));
j += "{ name: " + keys[i] + ", data: [" + archive.username + ", " + archive.email + ", " + archive.password + "]},";
i++;
}
var newString = j.substr(0, j.length - 1);
console.log('newString: ', newString);
Highcharts.chart('container', {
title: {
text: 'Datos ingresados'
},
subtitle: {
text: 'Localstorage'
},
yAxis: {
title: {
text: 'Datos ingresados'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 2017
}
},
series: [
newString
],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
});
This is what console.log shows:
{ name: 2, data: [12345, 23456, 34567]},{ name: 3, data: [23456, 34567, 45678]},{ name: 4, data: [34567, 45678, 56789]},{ name: 5, data: [45678, 56789, 67890]}
When I change the value of newString for that, it works properly.
Because in the second case, Highcharts see your data as a pure string. So, you need to parse your string.
But first of all, we should create valid json for parsing correctly:
var newString = "{ name: 2, data: [12345, 23456, 34567]}"; //bad json
var json = newString.replace(/(['"])?([a-zA-Z0-9]+)(['"])?:/g, '"$2":');
var goodJson = "[" + json + "]"; //valid json
Now we can create options for the Highcharts:
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: []
};
And push data to series as follows:
$.each(JSON.parse(goodJson), function(i, item) {
options.series.push({
name: item.name,
data: item.data
});
});
And finally initialize Highcharts:
var chart = new Highcharts.Chart(options);
See at Plunker

Categories

Resources