Highcharts with JSON to customize multiple series - javascript

I would like to add multiple series in my graph from a json file with 4 columns (date, open incident, closed incident and in progress incident).
I can show my graph with the number of incident open (http://jsfiddle.net/269us/) but I can't find the 3rd and 4th columns of JSON file.
Here is the structure of my JSON file:
[[1325462400000,3,12,14]
[1325548800000,7,14,8]
[1325635200000,10,11,24]
[1325721600000,21,13,16]
[1325808000000,13,15,9]
[1325894400000,2,15,4]
[1326067200000,10,13,15]]
I want to reach as a result of this type in order to customize each series (open, closed, in progress)
var date = []
open = []
close = []
inprogress = []
datalength = data.length;
for (i = 0; i <dataLength; i + +) {
date.push ([
data [i] [0]
]);
open.push ([
data [i] [1],
]);
close.push ([
data [i] [2],
]);
inprogress.push ([
data [i] [3],
]);
}
series: [{
type: 'spline',
name: 'open',
data: open,
dataGrouping {
units: groupingUnits
}
} {
type: 'column',
name: 'close',
data: close,
dataGrouping {
units: groupingUnits
}
.............
.............
}]

I think you are trying to create 3 data arrays to use in 3 series (open, close and in-progress). Try something like this:
for (i = 0; i <dataLength; i + +) {
var date = data[i][0];
open.push ([
date,
data[i][1]
]);
close.push ([
data,data[i][2] //data instead of dat.
]);
inprogress.push ([
date,data[i][3]
]);
}
You sould now be able to use these 3 arrays as the data in your series:
series: [{
type: 'spline',
name: 'open',
data: open,
dataGrouping {
units: groupingUnits
}
},
{
type: 'column',
name: 'close',
data: close,
dataGrouping {
units: groupingUnits
}
},
{
type: 'line',
name: 'inprogress',
data: inprogess,
dataGrouping {
units: groupingUnits
}
}

Related

Chart.js, returning an "date" array to plot the line graph

in the database I have 3 data which i send via Rest-API to the Frontend Angular.
This works fine.
Here in browser console, you can see all three dataset, which I get through node.js via Rest-API:
How it looks in the browser console
the result in the browser console looks like this:
0:
device_id: 2885679
list: Array(1)
0:
dt: 1596608643
main:
humidity: 10
pressure: 7.86
temp: 120.052
temp_max: 40.052
temp_min: 20.052
__proto__: Object
__proto__: Object
length: 1
__proto__: Array(0)
message: "1"
__v: 0
_id: "5f2a63857ce17d64d49465a4"
In the typescript component xy.component.ts my code looks like this:
export class ContactsComponent {
chart: any = [];
constructor(private contactService: ContactService) { }
ngOnInit() {
this.contactService.getContacts()
.subscribe((res: any[]) => {
console.log(res);
for (let i = 0; i < res.length; i++) {
let temp_max = res[i]['list'].map(res => res.main.temp_max);
let temp_min = res[i]['list'].map(res => res.main.temp_min);
let alldates = res[i]['list'].map(res => res.dt)
console.log(alldates)
let deviceData = []
alldates.forEach((res) => {
let jsdate = new Date(res * 1000)
deviceData.push(jsdate.toLocaleTimeString('en', { year: 'numeric', month: 'short', day: 'numeric' }))
})
console.log(deviceData)
this.chart = new Chart('canvas', {
type: 'line',
data: {
labels: deviceData,
datasets: [{
data: temp_max,
borderColor: '#3cba9f',
fill: false
}, {
data: temp_min,
borderColor: '#ffcc00',
fill: false
},
]
},
options: {
legend: {
display: false
},
scales: {
xAxes: [{
display: true
}],
yAxes: [{
display: true
}]
}
}
})
}
})
}
Why console.log(deviceData) only return the last value of the iteration?
I want to return all the values in console.log(devicedata) to draw a graph based on 3 timestamps. Here when I only get back 1 timestamp. Somehow it overwrites the values with the deviceData.push - Methode.
My goal is to draw all the datapoints i have (refer to the screenshots of the browser console).
Here how the graph is plot in the browser. It only plots one point, that is exactly the point of the console.log(deviceData):
graph
What is the problem and how can I fix it?
Thanks
Eden
It seems every object in res has a list with only a single item.
(res[i]['list'] is an array of length 1)
Try logging this:
(this takes all the values of each item and puts them in a single list)
let allvalues = [];
for (const item of res) {
for (const measurement of item.list) {
allvalues.push(measurement)
}
}
console.log(allvalues);

highcharts doesn't read data, works with fake data

I'm trying to make visualization of the voltage, Array has 1k elements but I'm testing it on first 10 for now, the thing is that It doesn't display anything, what's more interesting when I use fake date which is commented out now, It shows chart properly. I thought that perhaps there is some problem with array so tried to use Array.from but it also brought no effect, here is my code:
.then(function(res) {
var averageVoltage = []
var inputVoltage = []
var date = []
for (var i = 0; i < 10; i++) {
if (res[i].average_volatage !== undefined) {
averageVoltage.push(res[i].average_volatage)
date.push(res[i].timestamp)
}
}
console.log(averageVoltage)
console.log(date)
Highcharts.chart('battery_chart', {
chart: {
type: 'line'
},
title: {
text: id
},
yAxis: {
title: {
text: 'Measurement'
},
},
xAxis: {
categories: date
},
series: [{
name: 'Average Voltage',
data: averageVoltage
// data: [12283, 12283, 12281, 12280, 12282, 12283, 12281, 12282, 12281, 12280]
},
]
});
and that's how array is shown in console.log:
Your array should show up as [12283, 12281, 12280, etc.] in console as well, instead it shows up as [Number, Number, ...]. Try changing this line:
averageVoltage.push(res[i].average_volatage)
to:
averageVoltage.push(parseInt(res[i].average_volatage))
Additionally, instead of using dates as categories, it could be easier to use the highchart datetime axis. This would let you manipulate how you want the date displayed, have several series with different timestamps in one graph, and many other things. To get this to work, you could do this:
.then(function(res) {
var averageVoltage = []
var inputVoltage = []
for (var i = 0; i < 10; i++) {
if (res[i].average_volatage !== undefined) {
averageVoltage.push({x: new Date(res[i].timestamp).getTime(), y: parseInt(res[i].average_volatage)})
}
}
console.log(averageVoltage)
Highcharts.chart('battery_chart', {
chart: {
type: 'line'
},
title: {
text: id
},
yAxis: {
title: {
text: 'Measurement'
},
},
xAxis: {
type: 'datetime'
},
series: [{
name: 'Average Voltage',
data: averageVoltage
},
]
});

making large csv chartable by querying iso code in highcharts

I'm trying to load a csv and format it so it will display as a chart in highcharts, this is proving difficult because of the structure of the csv data.
Here is the csv: https://pastebin.com/Ynz7GJJh
Sample:
iso,type,year,affected
JAM,Earthquake,1907,90000
JAM,Storm,1912,94820
TON,Volcano,1946,2500
DZA,Earthquake,1954,129250
HTI,Storm,1954,250000
Here is my highcharts.ajax so far
var hsOptions = {
chart: {
type: 'column'
},
title: {
text: 'KEY NATURAL HAZARD STATISTICS'
},
subtitle: {
text: 'Number of People Affected'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Units'
}
},
series: []
};
Highcharts.ajax({
url: '/pathto.csv',
dataType: 'text',
success: function(csv) {
var rows = csv.split(/\r\n|\n/);
var cell;
var series = [];
var seriesBuilder = {name: countryValue, data: []};
for (var i = 0; i < rows.length; i++) {
cell = rows[i].split(',');
if (cell[0] === countryValue){
seriesBuilder.data.push(cell);
}
}
console.log(seriesBuilder);
series.push(seriesBuilder);
hsOptions.series.push(series);
Highcharts.chart('hazard-stats', hsOptions);
},
error: function (e, t) {
console.error(e, t);
}
});
which does make this
But I need this to build a series per disaster type, then the years have to combine on their own axis... it should be able to render just like this:

Two highchart update issue

I have two line chart that are identical and use same data.
I have written an update code that update both the charts:
c2updateLineGraph(2,[[0, 105993],[25, 659727],[50, 648727],[75, 636627],[100, 636627]]);
function c2updateLineGraph(index,data)
{
c2chart1.series[index].setData(data, true);
c2chart1p.series[index].setData(data, true);
}
My data structure is:
var c2graphdata=[{
name: 'Current year',
data: []
},
{
name: 'Reapair v1',
data: []
},
{
name: 'Repair v2',
data: []
},
{
name: 'Replacement v1',
data: []
},
{
name: 'Replacement v2',
data: []
},
{
name: 'Facelift v1',
data: []
},
{
name: 'Facelift v2',
data: []
},
{
name: 'Reconstruction v1',
data: []
},
{
name: 'Reconstruction v2',
data: []
},
];
Issue is c2chart1 is getting updated, but not c2chart1p. Trick is if I swap the position of c2chart1 and c2chart1p, then c2chart1p get updated only.
I could replicate the issue here jsfiddle.net/hhh2zx3w Check after 8 secs only chart1 gets updated, not chart2
Reset the graph data and setting the data agin will work for you . just change
function c2updateLineGraph(index, data) {
c2chart1.series[index].setData(data, true);
c2chart1p.series[index].setData(c2graphdata, true); //reset the graph data
c2chart1p.series[index].setData(data, true);
}
Updated fiddle:
http://jsfiddle.net/hhh2zx3w/2/
Hope it helps

Highcharts column drilldown

From my php file, my array prints something this:
Array
(
[2011] => Array
(
[name] => 2011
[total] => 963
[drilldown] => true
)
[2012] => Array
(
[name] => 2012
[total] => 1997
[drilldown] => true
)
[2013] => Array
(
[name] => 2013
[total] => 1188
[drilldown] => true
)
)
And this is the json_encode:
{"2011":{"name":2011,"total":963,"drilldown":"true"},
"2012":{"name":2012,"total":1997,"drilldown":"true"},
"2013":{"name":2013,"total":1188,"drilldown":"true"}}
from this working link: highcharts/drilldown
data: [{
name: 'Animals',
y: 5,
drilldown: true
}, {
name: 'Fruits',
y: 2,
drilldown: true
}, {
name: 'Cars',
y: 4,
drilldown: true
}]
I want to change this part with my json.
I have made a JSFIDDLE demo.
What you need to do is assign the json encoded string of PHP array to a javascript variable like this:
var my_data = <?php echo json_encode($php_array); ?>
on this the variable my_data will have values like:
var my_data = {
"2011":{"name":2011,"total":963,"drilldown":"true"},
"2012":{"name":2012,"total":1997,"drilldown":"true"},
"2013":{"name":2013,"total":1188,"drilldown":"true"}
};
now this object needs to be structured into the format so that highcharts can use it as data source for plotting the values for the graph. It can be done like this:
var data_array = [];
$.each(my_data, function(key, value){
var total_value = value.total;
delete value.total;//remove the attribute total
value.y = total_value;//add a new attribute "y" for plotting values on y-axis
data_array.push(value);
});
after this data_array will have structure like:
data_array = [
{"name":2011,"y":963,"drilldown":"true"},//note we have removed attribute "total" with "y"
{"name":2012,"y":1997,"drilldown":"true"},
{"name":2013,"y":1188,"drilldown":"true"}
];
and now this data_array can be passed as data source to the chart while initialization like this:
// Create the chart
$('#container').highcharts({
....
.....
series: [{
name: 'Things',
colorByPoint: true,
data:data_array//put the data_array here
....
..
and you are done !
Here is the complete code:
$(function () {
var data_array = [];
//assign the json encoded string of PHP array here like:
//var my_data = <?php echo json_encode($php_array); ?>
var my_data = {
"2011":{"name":2011,"total":963,"drilldown":"true"},
"2012":{"name":2012,"total":1997,"drilldown":"true"},
"2013":{"name":2013,"total":1188,"drilldown":"true"}
};
$.each(my_data, function(key, value){
//console.log("key = "+key);
//console.log("value=");
//console.log(value);
var total_value = value.total;
delete value.total;//remove the attribute total
value.y = total_value;//add a new attribute "y" for plotting values on y-axis
data_array.push(value);
});
//console.log("data_array = ");
//console.log(data_array);
// Create the chart
$('#container').highcharts({
chart: {
type: 'column',
events: {
drilldown: function (e) {
if (!e.seriesOptions) {
var chart = this,
drilldowns = {
'Animals': {
name: 'Animals',
data: [
['Cows', 2],
['Sheep', 3]
]
},
'Fruits': {
name: 'Fruits',
data: [
['Apples', 5],
['Oranges', 7],
['Bananas', 2]
]
},
'Cars': {
name: 'Cars',
data: [
['Toyota', 1],
['Volkswagen', 2],
['Opel', 5]
]
}
},
series = drilldowns[e.point.name];
// Show the loading label
chart.showLoading('Simulating Ajax ...');
setTimeout(function () {
chart.hideLoading();
chart.addSeriesAsDrilldown(e.point, series);
}, 1000);
}
}
}
},
title: {
text: 'Async drilldown'
},
xAxis: {
type: 'category'
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
}
}
},
series: [{
name: 'Things',
colorByPoint: true,
data:data_array
}],
drilldown: {
series: []
}
})
});

Categories