简体   繁体   中英

Highcharts column chart with additional labels in the middle of columns

My chart displays columns with min and max values:

plotOptions: {
    series: {
        dataLabels: {
            enabled: true,
            color: 'auto'
        }
    }
}

JSFiddle here

How can I display additional labels with average values in the middle of the corresponding columns?

You can use formatter in tooltip and plotOptions.series.dataLabels and use this.point.high and this.point.low to get the high and low of the serie and calculate the average:

formatter : function() {
     var res = "";
     if(this.point.high == this.y)
     res += "Average: " + (this.point.high + this.point.low)/2 + "<br><br><br><br>";
     res += this.y;
     return res;                        
}

Here's the DEMO

EDIT:

You cannot add another dataLabel in your chart. But, I managed to add the Average to one of your dataLabels and then using jQuery I changed it's position considering the amount of each average:

$.each($( "tspan:contains('Average')" ), 
    function(i, t) { t.setAttribute('dy', parseInt(t.textContent.slice(9))/135); });

Please see this DEMO

In general, it's not supported. However, you can extend Highcharts, so you will render any text you want to. Simple example for you: http://jsfiddle.net/8e0m2w5h/8/

(function (H) {
    // wrap drawDataLabels, which will draw dataLabels when required

    H.wrap(H.seriesTypes.columnrange.prototype, 'drawDataLabels', function (p) {
        var x, y, series = this;

        p.call(series);

        // loop over all points to generate or update your label
        H.each(series.data, function (point, i) {
            if (point.dataLabel && point.dataLabelUpper) {
                y = (point.plotLow + point.plotHigh) / 2;
                x = point.shapeArgs.x + point.shapeArgs.width / 2;


                if (point.dataLabelMiddle) {
                    // animate dataLabel after redraw/resize etc.
                    point.dataLabelMiddle.animate({
                        x: x,
                        y: y
                    });
                } else {
                    point.dataLabelMiddle = series.chart.renderer.text((point.low + point.high) / 2, x, y).attr({
                        align: 'center' //align dataLabel in the middle
                    }).add(series.dataLabelsGroup);
                }
            }
        });

    });
})(Highcharts);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM