Calculating a min y axis value in highcharts

谁都会走 提交于 2019-12-13 17:39:58

问题


If I create column chart that has values that are > 0 but much closer in value to each other than they are to 0 then the chart generated will have columns that look almost identical. See this jsFiddle.

However if I change the chart type to a line then the resulting chart is much nicer because the min yAxis value is calculated to a non-zero value so that the distribution of the values on the chart is much more obvious.

I could manually set a min yAxis value but I need this to work for any set of data and so it needs to be calculated. How could I achieve the same thing for a column chart?


回答1:


I've found where Highcharts calculates the min value for line charts (at least for linear axes). It's in the getTickPositions() function. Specifically these lines of code:

// pad the values to get clear of the chart's edges
if (!categories && !usePercentage && !isLinked && defined(min) && defined(max)) {
    length = (max - min) || 1;
    if (!defined(options.min) && !defined(userMin) && minPadding && (dataMin < 0 || !ignoreMinPadding)) {
        min -= length * minPadding;
    }
    if (!defined(options.max) && !defined(userMax)  && maxPadding && (dataMax > 0 || !ignoreMaxPadding)) {
        max += length * maxPadding;
    }
}

So it calculates the min as

length = ([max data value] - [min data value]) || 1
min = [min data value] - length * minPadding

The default for minPadding on the yAxis is 0.05 so

394.5 = 395 - ((405 - 395) * 0.05)

394.5 is rounded when creating the tick positions so the end result is 390.

What I've come up with so far is this. (The minPadding default on the yAxis doesn't seem to be exposed so I've hardcoded it)

var data = [400,405,395];

Array.max = function( array ){
    return Math.max.apply( Math, array );
};
Array.min = function( array ){
    return Math.min.apply( Math, array );
};

var min = Array.min(data);
var max = Array.max(data);

var chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container',
        defaultSeriesType: 'column'
    },
    yAxis: {
        min: min - ((max-min) * 0.05)
    },
    series: [{
        data: data
    }]
});



回答2:


Try setting the yAxis value, for example:

var chart = new Highcharts.Chart({

    chart: {
        renderTo: 'container',
        defaultSeriesType: 'column'
    },

    yAxis: {
       min: 390,
       startOnTick: false
    },

    series: [{
        data: [400,405,395]
    }]
});

You can also set it to some kind of dynamic value in javascript (AVG(400, 405, 395) - 10%, for instance) that should give it enough scale.

Updated JSFiddle is here. ​



来源:https://stackoverflow.com/questions/10222613/calculating-a-min-y-axis-value-in-highcharts

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!