I am passing a Json to highcharts
json: {"0":[{"name":"normal","data":["1647","270905","412080","13609","17062","20889","16","765097","13424","14","2044","630686","104019","3097","733","1462"]},{"name":"rft","data":[1300177,4599692,957739,4177103,3436151,3752121,1978772,1850918,2538336,521542,2951953,4108915,1516107,3329831,661657,3447965]}]}
and used this code to breakdown and passing to highcharts:
series: [{
data: (function() {
var chart_data =[];
$.each(obj[0], function (index, value) {
var arra=[];
// alert(value['name'])
arra['name']=value['name'];
arra['data']=[];
//alert(value['data'].length);
$.each(value['data'],function(ind,val){
arra['data'].push(parseInt(val));
});
//console.log(arra);
chart_data.push(arra);
});
return chart_data ;
})()
}]
but not working....
var arra=[];
// alert(value['name'])
arra['name']=value['name'];
This code shows you are treating an array (only number indices) as an object (string index). Try using:
var arra={};
// alert(value['name'])
arra['name']=value['name'];
First construct your JSON Data to exclude the keys "0" and "1" if that will be possible. Once done you can plot your graph as can be seen on this JSFiddle
var obj=[{"name":"normal","data":["1647","270905","412080","13609","17062","20889","16","765097","13424","14","2044","630686","104019","3097","733","1462"]},{"name":"rft","data":[1300177,4599692,957739,4177103,3436151,3752121,1978772,1850918,2538336,521542,2951953,4108915,1516107,3329831,661657,3447965]}];
$(function () {
$('#container').highcharts({
chart: {
type: 'spline'
},
title: {
text: 'Snow depth at Vikjafjellet, Norway'
},
subtitle: {
text: 'Irregular time data in Highcharts JS'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
},
title: {
text: 'Date'
}
},
yAxis: {
title: {
text: 'Snow depth (m)'
},
min: 0
},
tooltip: {
headerFormat: '<b>{series.name}</b><br>',
pointFormat: '{point.x:%e. %b}: {point.y:.2f} m'
},
series: (function(){
return obj;
})()
});
});
But if your JSON Data must be as it is currently, then you can change series to:
series: (function(){
return obj[0];
})()
Related
I am trying to use this chart to display my data - https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/spline-irregular-time
My data looks like this on the backend -
My chart looks like this
Notice the date on the x-axis is wrong and the date on the label always says 1 Jan for all datapoints. How do I fix this such that the date on the label and x-axis is correct. Here is my JS code
var credit = '<?php echo (isset($credit))?$credit:0; ?>'
Highcharts.chart('transactionId', {
chart: {
type: 'spline'
},
title: {
text: 'Snow depth at Vikjafjellet, Norway'
},
subtitle: {
text: 'Irregular time data in Highcharts JS'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
},
title: {
text: 'Date'
}
},
yAxis: {
title: {
text: 'Snow depth (m)'
},
min: 0
},
tooltip: {
headerFormat: '<b>{series.name}</b><br>',
pointFormat: '{point.x:%e. %b}: {point.y:.2f} m'
},
plotOptions: {
series: {
marker: {
enabled: true
}
}
},
colors: ['#6CF', '#39F', '#06C', '#036', '#000'],
// Define the data points. All series have a dummy year
// of 1970/71 in order to be compared on the same x axis. Note
// that in JavaScript, months start at 0 for January, 1 for February etc.
series: [{
name: "Winter 2016-2017",
data: JSON.parse(credit)
}],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
plotOptions: {
series: {
marker: {
radius: 2.5
}
}
}
}
}]
}
});
The problem is the date format 2020-12-13. Passing a date string directly doesn't work. You have to convert to Date.UTC(year, month, day) format.
So your credit array should look like this when passing to chart config.
credit = [
[Date.UTC(2020, 12, 13), 5000],
[Date.UTC(2020, 12, 19), 50000],
...
]
I am trying to show my x-axis values as a string on highcharts for a series but instead get (0,1,2....) which is the xaxis array index position. How do I show the xaxis value formatted as a string on higcharts?
Here is what I have
Highcharts.chart('container', {
title: {
text: 'Chart with time'
},
xAxis: {
type: 'datetime',
"labels": {
"formatter": function() {
console.log(this);
console.log(this.value.toString());
return this.value
}
},
},
series: [{
data: [
['Jan-1', 100],
['Jan-2', 120],
['Jan-3', 130]
]
}]
});
Would like to see 'Jan-1', 'Jan-2' as the labels on the x-axis. Here is a link to the fiddle below https://jsfiddle.net/dLfv2sbd/2/
Remove labels and use type: 'category' instead of type: 'datetime':
Highcharts.chart('container', {
title: {
text: 'Chart with time'
},
xAxis: {
type: 'category',
},
series: [{
data: [
['Jan-1', 100],
['Jan-2', 120],
['Jan-3', 130]
]
}]
});
Check the fiddle.
You can still use datetime this way.
Highcharts.chart('container', {
title: {
text: 'Chart with time'
},
xAxis: {
type: 'datetime',
"labels": {
"formatter": function() {
return Highcharts.dateFormat('%b-%e', this.value)
}
},
},
series: [{
data: [
[Date.UTC(2017,0,1), 100],
[Date.UTC(2017,0,2), 120],
[Date.UTC(2017,0,3), 130]
]
}]
});
https://jsfiddle.net/dLfv2sbd/4/
I am using HighCharts to visualize percentages from projects, which are downdrilled into variables which make the percentages!
I will give my code :
$(function () {
// Create the chart
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Comparison'
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
enabled: true,
text: 'Percentages',
style: {
fontWeight: 'normal'
}
},
labels: {
format: '{value}%'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.1f}%'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
},
series: [{
name: '',
colorByPoint: true,
data: []
}],
credits: {
enabled: false
},
drilldown: {
series: [{
name : '',
id: '',
data: []
}]
}
};
$.getJSON('/uploads/fraction.json', function (list) {
options.series = list;
});
$.getJSON('/uploads/drilldown.json', function (list2) {
options.drilldown.series = list2;
var chart = new Highcharts.Chart(options);
});
});
Example of the JSONs:
fraction.json
[{"name":"","colorByPoint":true,"data":[{"name":1,"y":80,"drilldown":1},{"name":2,"y":87,"drilldown":2},{"name":3,"y":105.71428571429,"drilldown":3},{"name":5,"y":"","drilldown":5},{"name":6,"y":53.160248409091,"drilldown":6}]}]
drilldown.json
[{"name":1,"id":1,"data":[["Total",2],["Estimated",2.5]]},{"name":2,"id":2,"data":[["Total",3.9],["Estimated",4.5]]},{"name":3,"id":3,"data":[["Total",3.7],["Estimated",3.5]]},{"name":5,"id":5,"data":[["Total",""],["Estimated",0.44]]},{"name":6,"id":6,"data":[["Total",0.233905093],["Estimated",0.44]]}]
I would like the graph to show percentages above the column and on the yAxis when the graph is first loaded, but absolute values when the drilldown is activated. I didn't manage to get it until now. Could you help me?
There are two ways of doing those changes - a static and dynamic way. Static way - define data labels and tooltip options for drilldown series.
Dynamic way - apply the options on drilldown/drillup events.
events: {
drilldown: function(options) {
this.yAxis[0].update({
labels: {
format: '{value}'
}
}, false, false);
options.seriesOptions.dataLabels = {
format: '{point.y:.1f}'
};
options.seriesOptions.tooltip = {
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}</b> of total<br/>'
};
},
drillup: function () {
this.yAxis[0].update({
labels: {
format: '{value}%'
}
}, false, false);
}
}
example: http://jsfiddle.net/d4fmaeea/
Two warnings:
In your json files, you have points which has value equals to "" which is not a valid type (must be number/null) and it may cause some issues, e.g. column with value 0 will have the same height as the column with value 10.
$.getJSON() is an asynchronous function. You use getJSON to assign list to options.series but that part may be executed after the chart was created so you would end up with the chart with no top-level series, only the drilldown ones.
Async part of code:
$.getJSON('/uploads/fraction.json', function (list) {
options.series = list;
});
$.getJSON('/uploads/drilldown.json', function (list2) {
options.drilldown.series = list2;
var chart = new Highcharts.Chart(options);
});
I have been trying to customize an excellent jsfiddle that I was fortunate enough to be directed to in an earlier question here: Switching between many Highcharts using buttons or link text
I am very new to javascript programming (and highcharts also) and I am having some difficulties in retrieving my own data from a database. Currently I have set up my charts like the following:
$('chart1').ready(function() {
var options = {
chart: {
renderTo: 'chart1',
type: 'column',
marginTop: 40,
marginBottom: 75
},
legend: {
enabled: false
},
title: {
text: 'Revenues',
x: 25 //center
},
xAxis: {
title: {
text: ''
},
categories: []
},
yAxis: {
showInLegend: false,
tickAmount: 11,
endOnTick: false,
startOnTick: true,
labels: {
formatter: function () {
return Highcharts.numberFormat(this.value, 0, '.', ',');
}
},
title: {
text: '<?php echo $unitCurr; ?>'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ Highcharts.numberFormat(this.y, 0,'.',',');
}
},
series: []
}
var tableName = '<?php echo $tableName; ?>'
$.getJSON("../../companies/charts/data.php", {id: escape(tableName)}, function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
});
});
At the bottom you will notice that I am using JSON to retrieve information from my database and everything works just fine. In my earlier question I was asking about how to switch charts using buttons instead and was directed to the following jsfiddle: http://jsfiddle.net/jlbriggs/7ntyzo6u/
This example consists of 3 charts but I have just been trying to manipulate the first chart in order to find out if I could make my own data display instead of the random data that is being generated:
var chart,
chartOptions = {},
chartData = {};
chartData.chart1 = randomData(25);
chartData.chart2 = randomData(10, true);
chartData.chart3 = randomData(65, true, 300);
chartOptions.chart1 = {
chart: {
type: 'column'
},
title: {
text: 'Chart 1 Title'
},
yAxis: {
title: {
text: 'Chart 1<br/>Y Axis'
}
},
series: [{
name: 'Chart 1 Series',
data: chartData.chart1
}]
};
But no matter how much I tried, I just can't seem to change the "data: chartData.chart1" in such a way that it retrieve the arrays I get from my $.getJSON function. Can any of you help me explain why, for instance, the below code doesn't work?. Here I try to exchange the ChartData.chart1 array for my database data. I'm not experienced enough to tell whether its the whole random number generation part of the code that prevents it from working or if it's my understanding thats severely lacking. (I have made sure that the data from data.php is indeed available, since I can display it in a normal array when I try).
var chart,
chartOptions = {},
chartData = {};
chartData.chart2 = randomData(10, true);
chartData.chart3 = randomData(65, true, 300);
$.getJSON("../../companies/charts/data.php", {id: escape(tableName)}, function(json) {
chartData.chart1 = json[6]['data'];
});
chartOptions.chart1 = {
chart: {
type: 'column'
},
title: {
text: 'Chart 1 Title'
},
yAxis: {
title: {
text: 'Chart 1<br/>Y Axis'
}
},
series: [{
name: 'Chart 1 Series',
data: chartData.chart1
}]
};
Any assistance you can provide will be greatly appreciated!
You're actually very close to something that will work. Your problem is related to the timing of async calls relative to inline code, and also the way assignments work in javascript.
As a quick example, here's some code:
x = {foo:5};
y = x.foo;
x.foo = 9;
At the end of this, x.foo is 9, but y is still 5.
Your line of code
chartData.chart1 = json[6]['data'];
doesn't execute until after the call to the server completes; it's contained within a call back function. However, this section of code
chartOptions.chart1 = {
chart: {
type: 'column'
},
title: {
text: 'Chart 1 Title'
},
yAxis: {
title: {
text: 'Chart 1<br/>Y Axis'
}
},
series: [{
name: 'Chart 1 Series',
data: chartData.chart1
}]
};
executes immediately. See the problem? You've cooked the current value of chartData.chart into chartOptions.chart1 BEFORE the server call has completed. That's why you're not seeing your data.
Instead, try something like this:
chartOptions.chart1 = {
chart: {
type: 'column'
},
title: {
text: 'Chart 1 Title'
},
yAxis: {
title: {
text: 'Chart 1<br/>Y Axis'
}
},
series: [{
name: 'Chart 1 Series',
data: []
}]
};
$.getJSON("../../companies/charts/data.php", {id: escape(tableName)}, function(json) {
chartOptions.chart1.series[0].data = json[6]['data'];
});
Now when your data comes back, you're putting it into the object that is actually being used to render the chart (once you click on the right button). Keep in mind that it's going to be empty until the server call completes.
I cannot get highcharts to recognize my timestamps, they are in javascript date format.
Tried many different approaches, but cannot get it to work when both the data and time array's are seperate.
Fiddle: http://jsfiddle.net/SjL6F/
$(function () {
Highcharts.setOptions({
lang: {
thousandsSep: ''
}
});
$('#container').highcharts({
title: {
text: 'Temperature - Last 24 hours',
},
credits: {
enabled: false
},
subtitle: {
text: "Test Site",
x: -20
},
xAxis: {
type: 'datetime',
labels: {
enabled: true
},
categories: time,
tickInterval: 3600 * 1000,
dateTimeLabelFormats: {
day: '%e of %b'
}
},
yAxis: [{
title: {
text: 'Temperature (\u00b0C)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
}],
tooltip: {
shared: true
},
series: [{
name: 'Temperature',
data: temp,
type: 'line',
tooltip: {
valueSuffix: ' C'
},
marker: {
enabled: false
}
}]
});
});
Highcharts just shows the raw javascript date value.
You are setting categories, which isn't datetime type for xAxis. Remove them, then concat time and temp arrays.
For example:
var concatenatedData = [];
$.each(time, function(i, e){
concatenatedData.push([parseInt(e), temp[i]]);
});
Demo:
http://jsfiddle.net/SjL6F/1/
Note: I have added parseInt, because Highcharts requires timestamps to be numbers, not strings.