【问题标题】:Highcharts - set yAxis.max to max value from dataHighcharts - 将 yAxis.max 设置为数据中的最大值
【发布时间】:2017-11-03 19:44:41
【问题描述】:

我正在使用 Highcharts,我有这个简单的条形图:

数据中的最大值为 27,但在比例尺上为 40。如何将 yAxis.max 设置为所提供数据的最大值?在这个例子中是 27 而不是 40。

说实话,我什至不需要图表上的这些值,但我想强制一个具有最大值的条占据 100% 的可用高度。

数据将动态提供,所以我不能手动设置最大值。

这是我当前的代码:

Highcharts.chart('container', {

  chart: {
    type: 'column',
    height: 150,
  },

  yAxis: {
    title: {
      text: null,
    },
    labels: {
      enabled: true,
    },
  },

  xAxis: {
    title: {
      text: null,
    },
  },

  credits: false,

  legend: false,

  title: {
    text: null,
  },

  series: [{
    data: [1, 0, 27, 7]
  }]
});
#container {
  min-width: 310px;
  max-width: 800px;
  height: 400px;
  margin: 0 auto
}
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container"></div>

这里是 jsfiddle:http://jsfiddle.net/de3qfb3r/

【问题讨论】:

    标签: javascript charts highcharts bar-chart


    【解决方案1】:

    你说你不关心图表上的值,所以也许添加 endOnTick: false 对你来说就足够了:

    yAxis: {
        title: {
            text: null,
        },
        labels: {
            enabled: true,
        },
        endOnTick: false
    }
    

    Highcharts 会自动计算最大值并将其拟合到可用高度。当 endOnTick 为真时(这是默认值),它会添加一个额外的空间以完成一个刻度

    【讨论】:

    • 这正是我所需要的。谢谢!
    【解决方案2】:

    如果你手头有数据,你可以找到数组的最大值。这里的一个问题是,如果不添加滴答间隔,我无法让 yAxis max 工作。以下是您如何实现此目的的示例。

    var data = [1, 0, 27, 7];
    var yMax = data.reduce(function(a, b) {
        return Math.max(a, b);
    });
    
    Highcharts.chart('container', {
    
        chart: {
            type: 'column',
            height: 150,
        },
    
        yAxis: {
            title: {
                text: null,
            },
            labels: {
                enabled: true,
            },
            tickInterval: 2,
            max: yMax
        },
    
        xAxis: {
            title: {
                text: null,
            },
        },
    
        credits: false,
    
        legend: false,
    
        title: {
            text: null,
        },
    
        series: [{
            data: data
        }]
    });
    #container {
    	min-width: 310px;
    	max-width: 800px;
    	height: 400px;
    	margin: 0 auto
    }
    <script src="https://code.highcharts.com/highcharts.js"></script>
    <script src="https://code.highcharts.com/modules/series-label.js"></script>
    <script src="https://code.highcharts.com/modules/exporting.js"></script>
    
    <div id="container"></div>

    【讨论】:

    • 它确实有效,但我认为 Pedro 的解决方案要好一些,因为它不需要除 highcharts 之外的额外代码。不过谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 2011-10-14
    • 2017-05-17
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    相关资源
    最近更新 更多