How to set a static minimum value for axes in Highcharts

后端 未结 2 1722
無奈伤痛
無奈伤痛 2020-12-09 21:40

I have time-based data that ranges from 1 to 500. Time is plotted on the x axis and the values are on the y axis.

When the range between the minimum and maximum data

相关标签:
2条回答
  • 2020-12-09 22:09

    I am amazed how difficult this is. Not an optimal solution, but the best I can dream up with HighChart's api:

    var someData = [1,5,82,9,300,5,42,199,5,6,99,1,56,52,250,64];
    
    var chart = new Highcharts.Chart({
    
        chart: {
            renderTo: 'container'
        },
        yAxis:{
            min: -10,
            tickInterval: 1,
            labels: {
                formatter: function() {
                    if (this.value < someData[0])
                        return null;
                    else if (this.value == someData[0])
                        return this.value;
                    else if (this.value % 50 == 0)
                        return this.value;
                }
            }
        },
        series: [{
            data: someData
        }]
    
    });
    

    enter image description here

    0 讨论(0)
  • 2020-12-09 22:14

    A solution (that optimizes Marks answer) is to use yAxis.labels.formatter with this.isFirst and this.axis.dataMin, like this:

    yAxis:{
        labels: {
            formatter: function() {
                if(this.isFirst)
                    return this.axis.dataMin;
                return this.value;
            }
        }
    }
    

    See this JSFiddle demo for an example.

    The advantage of this is that you do not have to manually set tickInterval, which saves a lot of calls to formatter and lets Highcharts figure out the label intervals itself. Also, it uses the axis knowledge of the minimum data value, instead of having to check against an array (which you may have to iterate over to find the minimum).

    Beware that the yAxis.min must be set to something sensible here (works best with 0, and positive data). If the y-axis goes far below the minimum datapoint the first label will not be the one at 0.

    The this.axis value was not available when this question was asked.

    0 讨论(0)
提交回复
热议问题