Search code examples
highchartsangular2-highcharts

Sync max min between many highcharts charts (in real time)


First of all I know about the sync tables example here: https://www.highcharts.com/demo/synchronized-charts

This is good but in my tables the Y axis is the same for all of the charts, the only problem is that each few seconds I dynamically add a point to each graph so I am looking for a way to have the same min and max for all of the charts (easier to compare).

I hooked into the afterSetExtremes() https://api.highcharts.com/highcharts/yAxis.events.afterSetExtremes
And then calculated the min of all the mins and the max of all the maxes (from all the charts together) and I forced it as the new min and max for all the charts.

The problem is that once I use setExtremes: https://api.highcharts.com/class-reference/Highcharts.Axis#setExtremes
Highcharts will stop calculating new mins and maxes which means that if the data in all of my charts is starting to shrink the max won't get re-calculated ever so the graphs will look kinda bad and hard to read (imagine max of 10k with data that is now around 1k in all of the charts).

I have an idea on how to solve it by reading the dataMin and dataMax props from highcharts for all the charts I have on my page and then calculating the min and max by myself each X seconds, my problem is that highcharts has some interesting way to calculate the max and min from dataMin and dataMax and I didn't find where it is defined or how I can use that function.

For example if in highcharts dataMax is 16442 then I believe the max would be 17500, I am not sure the exact logic that highcharts is doing there but I would like to keep the exact same behaviour.

tl;dr
1) What is the best way to sync min and max (Y axis) for different charts (but same units)?
2) If my solution here is the best approach then how can I use highcharts inner setMax from dataMax logic?

Thanks in advance!


Solution

  • It seems that you used setExtremes in the wrong place. Please take a look at my approach below, the charts have the same yAxis min and max every time you add a point:

    function synchronizeCharts() {
        var charts = Highcharts.charts,
            min, 
            max;
    
        Highcharts.each(charts, function(chart) {
            min = min ? Math.min(min, chart.yAxis[0].min) : chart.yAxis[0].min;
            max = max ? Math.max(max, chart.yAxis[0].max) : chart.yAxis[0].max;
        });
    
        Highcharts.each(charts, function(chart){
            if (chart.yAxis[0].min !== min || chart.yAxis[0].max !== max) {
                chart.yAxis[0].setExtremes(min, max);
            }
        });
    }
    

    Live demo: http://jsfiddle.net/BlackLabel/t81Lp20k/

    API: https://api.highcharts.com/class-reference/Highcharts.Axis#setExtremes

    If you still need to find out how Highcharts calculate extremes, you can look at the source code: https://code.highcharts.com/highcharts.src.js