Search code examples
javascripthighchartszoomingscatter-plot

Zoom xy proportionally in Highcharts scatter plot


Having a scatterplot:

https://jsfiddle.net/hdq4rc35/

I want to be able to zoom only proportionally xy, so the distance between y ticks is the same as x ticks at any time, resulting in a square zoom field instead of a free rectangle.

I tried chart.setExtremes() but it didn't affect the zoom functionally.


Solution

  • That functionality is not supported in Highcarts by default, but you can add it by wrapping drag method from Pointer prototype, for example:

    (function(H) {
      H.wrap(H.Pointer.prototype, 'drag', function(proceed, e) {
        var chartX = e.chartX,
          chartY = e.chartY,
          mouseDownX = this.mouseDownX,
          mouseDownY = this.mouseDownY,
          rectX = Math.abs(chartX - mouseDownX),
          rectY = Math.abs(chartY - mouseDownY);
    
        if (rectX > rectY) {
          e.chartY = chartY + (
            mouseDownY > chartY ?
            -(rectX - rectY) :
            (rectX - rectY)
          );
        } else {
          e.chartX = chartX + (
            mouseDownX > chartX ?
            -(rectY - rectX) :
            (rectY - rectX)
          );
        }
    
        proceed.apply(this, Array.prototype.slice.call(arguments, 1));
      });
    }(Highcharts));
    

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

    API Reference: https://www.highcharts.com/docs/extending-highcharts/extending-highcharts