Home Forums Report Bugs Secondary Axis and negative values

Secondary Axis and negative values

Viewing 3 posts - 1 through 3 (of 3 total)
  • #60605

    Hello,
    If I have negative values in a chart with a secondary axis, then the Y Axis do not align at 0
    https://jsfiddle.net/mx74fkvg/

    It was suggested on the general forum that setting a minimum value can resolve the issue.
    Like this https://jsfiddle.net/ngtmLrqz/

    However this requires calculating the interval & number of intervals. This is quite a burden to emulate

    Can issue be fixed?

    thanks

    #60610

    @mrdavid,

    Aligning the zero value across multiple y-axes is not available as an inbuilt feature as of now. However, you can align it by setting minimum, maximum and interval of the axes dynamically as shown in the code snippet below.

    
    var allAxes = [...chart.axisY, ...chart.axisY2];
    
    allAxes.forEach(axisInstance => {
      var initialMin = axisInstance.get("minimum");
      var initialMax = axisInstance.get("maximum");
      var initialInterval = axisInstance.get("interval");
    
      var newMin, newMax;
    
      if (initialMin >= 0) {
        newMin = (-initialMax * desiredFraction) / (1 - desiredFraction);
        newMax = initialMax;
      } else if (initialMax <= 0) {
        newMin = initialMin;
        newMax = (initialMin * (desiredFraction - 1)) / desiredFraction;
      } else {
        newMin = Math.min(
          initialMin,
          (-initialMax * desiredFraction) / (1 - desiredFraction)
        );
        newMax = (-newMin * (1 - desiredFraction)) / desiredFraction;
    
        // Ensure newMax doesn't undershoot data
        if (newMax < initialMax) {
          newMax = initialMax;
          newMin = (-newMax * desiredFraction) / (1 - desiredFraction);
        }
      }
    
      // Update axis values & re-render
      axisInstance.set("minimum", newMin, false);
      axisInstance.set("maximum", newMax, false);
      axisInstance.set("interval", initialInterval);
    });

    Also check out this JSFiddle for the complete working code.

    Aligning Zero Value across Multiple Y-Axes in chart

    —-
    Manoj Mohan
    Team CanvasJS

    #60633

    @Manoj,

    That works great. Thankyou for the detailed solution

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.