-->

Set highcharts y-axis min value to 0, unless there

2020-08-09 08:47发布

问题:

I'm having an issue with highcharts where I have a number of different charts being generated by JSON calls.

For the majority of these charts I need the minimum y-axis value to be set at 0, however there are a couple of occasions where negative values need to be shown. How can I tell highcharts to have a minimum y-axis value of 0 only if there are no negative values in the data, is this even possible?

Thanks

回答1:

The option that you're looking for is called softMin and was introduced in version 5.0.1. The docs describe it as follows:

A soft minimum for the axis. If the series data minimum is greater than this, the axis will stay at this minimum, but if the series data minimum is lower, the axis will flex to show all data.

yAxis: {
    softMin: 0
}

http://api.highcharts.com/highcharts/yAxis.softMin



回答2:

You can add to your y-axis :

 yAxis: {
            title: {
                text: 'Title of the y-axis'
            },
            min: 0 // this sets minimum values of y to 0
        },


回答3:

I achieved this by creating a function using setExtremes

var setMin = function () {
  var chart = this,
  ex = chart.yAxis[0].getExtremes();

  // Sets the min value for the chart 
  var minVal = 0;

  if (ex.dataMin < 0) {
    minVal = ex.dataMin;
  }

  //set the min and return the values
  chart.yAxis[0].setExtremes(minVal, null, true, false);
}

then in your chart, you call it like this:

$('#container').highcharts({ 
  chart: {
    events: {
      load: setMin
    }
  },
});  


回答4:

You can set the "floor", this defines the minimum possible value for min. When negative values are added, they will not be visible! (http://api.highcharts.com/highcharts/yAxis.floor)

yAxis: {
    floor: 0
}

I know this question has been asked a long time ago and this property did not exist at the time. But I just encounter this problem and I think others will be happy to not having to search.



回答5:

You can prepare your own function which check is negative is or not, then set appropriate ticks. To achive this, you should use tickPositioner http://api.highcharts.com/highcharts#yAxis.tickPositioner