Maximum bar width in Highcharts column charts

2019-04-03 08:53发布

I'm using Highcharts to create some vertical bars (a.k.a. "column charts") a lot like here: highcharts.com/demo/column-basic

Thing is, sometimes there are 30 bars in the chart, sometimes only two. Where then are two really wide bars in the chart, it looks really weird, so the decision was made to set a maximum width for the bars. That way if there are only two then they wouldn't get wider than, say, 50px, but if there were 50 then Highcharts could size them in the way it sees fit.

So my problem is that Highcharts doesn't have a way to explicitly set the maximum width of the columns. Has anyone found a solution to that?

8条回答
冷血范
2楼-- · 2019-04-03 09:49

Ultimate solution is to wrap drawPoints and overwrite shaperArgs of each point, especially x-position and width:

(function(H) { 
    var each = H.each;
    H.wrap(H.seriesTypes.column.prototype, 'drawPoints', function(proceed) {
        var series = this;
        if(series.data.length > 0 ){
            var width = series.barW > series.options.maxPointWidth ? series.options.maxPointWidth : series.barW;
            each(this.data, function(point) {
                point.shapeArgs.x += (point.shapeArgs.width - width) / 2;
                point.shapeArgs.width = width;
            });
        }
        proceed.call(this);
    })
})(Highcharts)

Use:

$('#container').highcharts({
    chart: {
      type: 'column'
    },
    series: [{
        maxPointWidth: 50,
        data: [ ... ]
    }]
});

And live demo: http://jsfiddle.net/83M3T/1/

查看更多
一纸荒年 Trace。
3楼-- · 2019-04-03 09:53
function(chart){
        var series = chart.series[0];
        //--- Enforce a Maximum bar width
        if (series && series.data.length) {
            if (series.data[0].pointWidth  >  MaximumBarWidth) {
                for(var i=0;i< chart.series.length;i++)
                  chart.series[i].update({
                    pointWidth:MaximumBarWidth
                    });
            }
        }
    }

http://jsfiddle.net/pXZRV/40/

查看更多
登录 后发表回答