highcharts

Highcharts - Keep Zero Centered on Y-Axis with Negative Values


I have an area chart with negative values. Nothing insanely different from the example they give, but there's one twist: I'd like to keep zero centered on the Y axis.

I know this can be achieved by setting the yAxis.max to some value n and yAxis.min to −n, with n representing the absolute value of either the peak of the chart or the trough, whichever is larger (as in this fiddle). However, my data is dynamic, so I don't know ahead of time what n needs to be.

I'm relatively new to Highcharts, so it's possible I'm missing a way to do this through configuration and let Highcharts take care of it for me, but it's looking like I'll need to use Javascript to manually adjust the y axis myself when the page loads, and as new data comes in.

Is there an easy, configuration-driven way to keep zero centered on the Y axis?


Solution

  • I ended up finding a way to do this through configuration after digging even further into the Highcharts API. Each axis has a configuration option called tickPositioner for which you provide a function which returns an array. This array contains the exact values where you want ticks to appear on the axis. Here is my new tickPositioner configuration, which places five ticks on my Y axis, with zero neatly in the middle and the max at both extremes :

    yAxis: {
    
        tickPositioner: function () {
    
            var maxDeviation = Math.ceil(Math.max(Math.abs(this.dataMax), Math.abs(this.dataMin)));
            var halfMaxDeviation = Math.ceil(maxDeviation / 2);
    
            return [-maxDeviation, -halfMaxDeviation, 0, halfMaxDeviation, maxDeviation];
        },
    
        ...
    }