Search code examples
javascriptreactjshighcharts

highcharts tilemap logarithmic colorAxis fails when 0


I'm trying to implement a tilemap in highcharts with a logarithmic colorAxis, however, I keep getting highcharts error #10 (can't plot zero or subzero values on a logarithmic axis).

Can i somehow get around this error? There is almost nothing about this error in docs.

My colorAxis now look like this:

"colorAxis": {
    "min": 4849377.1,
    "max": 160000000.3,
    "type": 'logarithmic',
    "minColor": '#EEEEFF',
    "maxColor": '#000022',
    "stops": [
      [0, '#A9A9FF'],
      [0.5, '#4444FF'],
      [1, '#000022']
    ]
},

Solution

  • Yes, you can add the below plugin and enable the allowNegativeLog option for color axis.

    (function(H) {
      H.addEvent(H.Axis, 'afterInit', function() {
        const logarithmic = this.logarithmic;
    
        if (logarithmic && this.options.allowNegativeLog) {
    
          // Avoid errors on negative numbers on a log axis
          this.positiveValuesOnly = false;
    
          // Override the converter functions
          logarithmic.log2lin = num => {
            const isNegative = num < 0;
    
            let adjustedNum = Math.abs(num);
    
            if (adjustedNum < 10) {
              adjustedNum += (10 - adjustedNum) / 10;
            }
    
            const result = Math.log(adjustedNum) / Math.LN10;
            return isNegative ? -result : result;
          };
    
          logarithmic.lin2log = num => {
            const isNegative = num < 0;
    
            let result = Math.pow(10, Math.abs(num));
            if (result < 10) {
              result = (10 * (result - 1)) / (10 - 1);
            }
            return isNegative ? -result : result;
          };
        }
      });
    }(Highcharts));
    
    Highcharts.chart('container', {
      ...,
      "colorAxis": {
        ...,
        allowNegativeLog: true
      }
    });
    

    Live demo: https://jsfiddle.net/BlackLabel/xtdobza1/

    Error info: https://assets.highcharts.com/errors/10/