Search code examples
maxhighchartsminapproximation

Highstock custom min max approximation works properly only at some ranges


I am feeding highstock chart with datas from mysql. There are variables stored every minute so if you want to look at data past 3 months they are grouped. Highstock's default approximation functions give low,high,averare,sum values only. I min and max values are most important for me so I made my own approximation function which is:

         approximation: function (arr) {
                 // first time or point precalculated          
                if ( !gInfo || gInfo.nextPoint) {
                    // first time return first value (arr[0])
                    var point = gInfo ? gInfo.nextPoint : arr[0];
                    // save current data to the next iteration    
                    gInfo = {prev : arr, nextPoint : null};
                    return point;
                } else {
                    var prev = gInfo.prev,
                        // concat current group with the previous one
                        data = prev.concat(arr),
                        // get min, max and their positions        
                        min = Math.min.apply(null, data),
                        max = Math.max.apply(null, data),
                        minIdx = data.indexOf(min),
                        maxIdx = data.indexOf(max),
                        // order min and max
                        aprox = minIdx < maxIdx ? [min, max] : [max, min];
                    // save next aproximation and return current
                    gInfo.nextPoint = aprox[1];
                    return aprox[0];
                }
        },

Actually I didn't make it but I found it here in the forum.

The problem is it gives me right results only at some ranges as shown in the pictures below:

First picture at max range - not ok: Max range - you can't see every min value

As I am changing range to smaller I can see every min value: This is how it should looke like at max range

It is also happening when I zoom in so datas are grouped in two min intervals and I am just scrolling to the left or to the right.

At first I thought that it has something to do with the way groups are made by changing groupPixelWidth: to any value did not help.

Having min or max is really important for me and this is something I can solve in highstock.


Solution

  • There seems to an error in approximation function. In 3rd line:

    if ( !gInfo || gInfo.nextPoint) {
    

    if should evaluate to false if !gInfo is false (it is after first time) AND gInfo.nextPoint returns false, but it will return false not only if it is null (as set in function), but also when it is zero. Changing if condition to:

    if (!gInfo || gInfo.nextPoint !== null) {
    

    Example with error (before the fix): http://jsfiddle.net/p2qvx24a/1/

    Example with fix: http://jsfiddle.net/p2qvx24a/