Highchart xAxis label steps wrong - javascript

I am loading Highcharts like this.
var options = {
credits: {
enabled: false
},
chart: {
renderTo: 'chart_box',
type: 'areaspline'
},
title: {
text: ''
},
xAxis: {
crosshairs: true,
labels: {
step: 5,
rotation: -45
}
},
series: []
};
Then I have a function which is called when graph needs to be loaded. Upon calling the function, data is fetched through AJAX and assigned to series and date lie this:
$.ajax({
url: 'url/charts',
type: 'post',
data: data
}).done(function(data) {
var dateCount = data.dates.length;
var stepCount = 1;
if (dateCount > 10) {
stepCount = 5;
}
options.xAxis.categories = data.dates;
$.each(data.series, function(name, elem) {
options.series.push({
name: name.replace('_', ' ').toUpperCase().trim(),
data: elem
})
});
chart = new Highcharts.Chart(options);
});
The issue here is that even though I have given step as 5 , it is showing dates with 15 dates interval. I mean in xAxis labels. It seems like it will be multiplied by three always. If I give 2, it will show 6 days interval in labels. Everything working fine in a chart which is not using AJAX to load data.

Related

Highcharts Not displaying function's data values

i Have created a Highchart using the Following Highchart's Demo:
https://www.highcharts.com/demo/dynamic-update
Now What I did I created my Own function to add dynamic values to the Chart.
I created a function to get the dynamic data from a particular php file whose data changes on every page load event.
I am getting the data values in the getData function console.log
Here is the Script That I am using.
<script type="text/javascript">
$(document).ready(function(){
function getData(){
$.ajax({
type: 'GET',
url: 'data.php',
success: function(data){
// var number = document.write(data) ;
console.log(data);
return data ;
}
}) ;
}
Highcharts.chart('chart', {
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = getData();
console.log(y);
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
time: {
useUTC: false
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
headerFormat: '<b>{series.name}</b><br/>',
pointFormat: '{point.x:%Y-%m-%d %H:%M:%S}<br/>{point.y:.2f}'
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: getData()
});
}
return data;
}())
}]
});
});
</script>
Now as you can see that I have created a getData function and getting the data value in return.
On console log under the getData function, I am getting integer Value in return every one second.
the problem is that under the Highchart's function, I am not able to get the data values using getData function, it's returning undefined in the console .
Highchart's is running but it does not show any data points. it is moving but without showing any data points.
Please correct me in the area , where I am doing wrong.
Any help is appreciated. Thanks
ajax calls are run asynchronously so you cant really return data from it.
instead you should render chart inside the ajax success function.
A good example is here already.
https://www.highcharts.com/docs/working-with-data/live-data
Basically
1. point on load to call a function getData
2. in Getdata call ajax function.
3. in success of ajax render chart with new data.
document.addEventListener('DOMContentLoaded', function() {
chart = Highcharts.chart('container', {
chart: {
type: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
/**
* Request data from the server, add it to the graph and set a timeout
* to request again
*/
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second - add this if you want to auto refresh
// setTimeout(requestData, 1000);
},
cache: false
});
}

dynamic chart with Highcharts using json

I've a question about how to create a dynamic chart using json, I tried and my graph didn't show a result, when I checked out, I've no error with my code. This is my code :
<script>
var chart; // global
function requestData() {
$.ajax({
url: 'api_heartrate.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is longer than 20
// add the point
chart.series[0].addPoint(eval(point), true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
</script>
</head>
<body>
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>`
this is my json :
http://health.barrukurniawan.tech/api_heartrate.php
[{"time":"2018-08-02 09:30:11","nilai_sensor":"78"}]
I tried following a tutorial from this link :
Highcharts Dynamic Chart with MySQL Data doesn't reload
Thanks for your attention, gladly waiting for an answer :)
There are multiple small errors in your approach
eval is bad, parse it using JSON.parse instead.
During load, chart is not defined yet, so your callback will not work.
Highcharts needs time in milliseconds since 1970.
highcharts expects an object {x: , y: ,...} you give it {time: , nilai_sensor: }.
Solutions:
point = JSON.parse(point)
events: {
load: function() {
setInterval(function() {
requestData(chart)
}, 1000);
}
}
new Date(point[0].time).getTime()
{x: new Date(point[0].time).getTime(), y: point[0].nilai_sensor}
Here is a working example using your input with static data(and some added time to keep it moving): https://jsfiddle.net/ewolden/md975oLk/23/

Highcharts showing ticks number, instead of date

I'm trying to create a graph from JSON received from a web API.
I had it working, and then decided to start refactoring.
After a while I suddenly noticed that the xAxis no longer shows dates, but instead it seems to be showing ticks.
I'm quite inexperienced with JavaScript and even more so with highcharts so I cannot spot my mistake.
(source: mortentoudahl.dk)
The change I did was making an option object, and pass it to highcharts upon instantiation, according to the instructions found here:
http://www.highcharts.com/docs/getting-started/how-to-set-options
When I compare my code to the last code block in that link, it seems to be the same, except for the options object.
var pm10 = [];
var pm25 = [];
var options = {
chart: {
zoomType: 'x',
renderTo: 'container'
},
title: {
text: "Compounds in the air at HCAB"
},
subtitle: {
text: document.ontouchstart === undefined ? 'Click and drag in the plot area to zoom in' : "Pinch the chart to zoom in"
},
xAxix: {
type: 'datetime'
},
yAxis: {
title: {
text: 'µg/m³'
}
},
series: [{
name: 'Particles less than 2.5 µm',
data: pm25,
pointStart: Date.UTC(2016, 5, 8),
pointInterval: 86400 * 1000 // One day
}, {
name: 'Particles less than 10 µm',
data: pm10,
pointStart: Date.UTC(2016, 5, 8),
pointInterval: 86400 * 1000 // One day
}]
};
function ReverseAndSetArrays(data) {
$.each(data.reverse(), function(key, value) {
if ("PM10b" in value) {
pm10.push(value["PM10b"]);
};
if (!("PM10b" in value)) {
pm10.push(null);
};
if ("PM25b" in value) {
pm25.push(value["PM25b"]);
};
if (!("PM25b" in value)) {
pm25.push(null);
};
});
};
var url = "super secret url";
$.getJSON(url, function(data) {
ReverseAndSetArrays(data);
var chart = new Highcharts.Chart(options);
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//code.highcharts.com/highcharts.js"></script>
<div id="container"></div>
The following configuration in your options object is incorrect:
xAxix: {
type: 'datetime'
}
It should be:
xAxis: {
type: 'datetime'
}

Highchart ID does not update with new variable

I try to generate a windrose on my website using highcharts. It should display the direction with an arrow and the speed in the gauge itself.
I have the following code to generate the charts:
$(document).ready(function() {
var chart = new Highcharts.Chart({
\\ some other parameters not relating to question
series: [{
data: [{
id: 'wnddr',
y: winddir,
dial: {
radius: '90%',
baseWidth: 3,
baseLength: '95%',
rearLength: 0
}
}],
dataLabels: {
enabled: true,
formatter : function(){
return windspd + ' km/u';
}
}
}]
},
function (chart){
setInterval(function() {
$.ajax({
type: "POST",
url: "example.php",
dataType: "JSON",
cahce: "false",
success: function(data){
windspd = data.query.results.channel.wind.speed;
winddir = data.query.results.channel.wind.direction;
windchill = data.query.results.channel.wind.chill;
hum = data.query.results.channel.atmosphere.humidity;
druk = data.query.results.channel.atmosphere.pressure;
ss = data.query.results.channel.astronomy.sunset;
sr = data.query.results.channel.astronomy.sunrise;
temp = data.query.results.channel.item.condition.temp;
des = data.query.results.channel.item.forecast[0].code;
var point = chart.series[0].points[0];
point.update(winddir);
// alert(winddir);
}
});
$('.update').html("<img src=http://l.yimg.com/a/i/us/we/52/" +des+ ".gif />");
}, 5000);
});
});
With wnddr.update(winddir); I was trying to update the winddir-variable in my chart. However, I can't get it to work. Also the alert does not pop-up so probably my code gets stuck just before. If I comment the two line above the alert out, the alert will work. Same goes for the speed-variable. Problem here is that is doesn't have a id-attribute.
I modified the code from highcharts as the basis. Giving 'y' a value by hand generates a valid and correct gauge. The same goes for a fixed value of winddir.

Put 2 lines on highchart with ajax and dynamic updating

I'm trying to put a second line on a Highchart using ajax with dynamic (periodic) updating. First line works fine using ajax. I think the problem is the format of the incoming data, but also how I'm splitting the data for each of the lines.
I have control of the format of the ajax data so it be could posted in most any form but it works for the first line.
Here is the ajax data that is received with each request:
[Date.parse("2013/02/14 14:29:00 -0000"), 51, 216510]
This will create a point for the first line at 51 but not anything for the second line which should be at 216510.
The following is the javascript I'm using:
var chart; // global
/**
* Request data from the server, add it to the graph and set a timeout to request again
*/
function requestData() {
$.ajax({
url: '/htbin/count_since_total',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 30; // shift if the series is longer than 300 (drop oldest point)
// add the point
chart.series[0].addPoint(eval(point), true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
events: {
load: requestData
}
},
title: {
text: 'time'
},
xAxis: {
type: 'datetime'
},
yAxis: [{ // Primary yAxis
title: {text: 'count'},
opposite: false
}, { // Secondary yAxis
title: {text: 'Total'},
opposite: true
}],
series: [{
yAxis: 0,
name: 'number',
data: []
},{
yAxis: 1,
name: 'Total',
data: []
}],
});
});
EDIT 1:
Not working, no second line with suggested changes. I'm thinking that incoming data format is incorrect or it needs processing after receiving. Also how does the data get assigned to the proper line?
series: [{
yAxis: 0,
name: 'number',
data: []
},{
yAxis: 1,
name: 'Total',
data: []
}],
--------- end EDIT 1 ----------------
In your success-action/function, you are only updating series[0].
If you want to add a point to the second line, you'll have to add a point to series[1] as well.
Add a for loop to do the same for each serie.
success: function(point) {
for(var i = 0, length = chart.series.length; i < length; i++) {
var serie = chart.series[i],
// shift if the series is longer than 300 (drop oldest point)
var shift = serie.data.length > 30;
// add the point
serie.addPoint(eval(point), true, shift);
}
// call it again after one second
setTimeout(requestData, 1000);
}

Categories