HighCharts饼图中的值总和

时间:2014-08-22 17:05:04

标签: javascript charts highcharts

有没有办法在图例或饼图中的任何其他位置获取总值?  这是带有图例的代码,但不是添加总百分比,而是要显示值的总和..

$(function () {
    var chart = new Highcharts.Chart({

        chart: {
            renderTo: 'container',
            type: 'pie',
            width: 500,
            borderWidth: 2
        },

        title: {
            text: 'demo'
        },

        credits: {
            enabled: false
        },

        legend: {

            layout: 'vertical',
            align: 'right',
            verticalAlign: 'top',
            y: 30,
            labelFormat: '{name} ({percentage:.1f}%)',
            navigation: {
                activeColor: '#3E576F',
                animation: true,
                arrowSize: 12,
                inactiveColor: '#CCC',
                style: {
                    fontWeight: 'bold',
                    color: '#333',
                    fontSize: '12px'    
                }
            }
        },
    tooltip: {
            formatter: function() {
                return Highcharts.numberFormat(this.percentage, 2) + '%<br />' + '<b>' + this.point.name + '</b><br />Rs.: ' + Highcharts.numberFormat(this.y, 2);
            }
        },
        series: [{
            data: (function () {
                var names = 'Ari,Bjartur,Bogi,Bragi,Dánjal,Dávur,Eli,Emil,Fróði,Hákun,Hanus,Hjalti,Ísakur,' +
                    'Johan,Jóhan,Julian,Kristian,Leon,Levi,Magnus,Martin,Mattias,Mikkjal,Nóa,Óli,Pauli,Petur,Rói,Sveinur,Teitur',
                    arr = [];

                Highcharts.each(names.split(','), function (name) {
                    arr.push({
                        name: name,
                        y: Math.round(Math.random() * 100)
                    });
                });

                return arr;
            }()),
            showInLegend: true
        }]

    });
});

2 个答案:

答案 0 :(得分:9)

我会使用Renderer.text来注释图表(而不是在图例中这样做,因为你有这么多的数据点)。

chart: {
    events: {
        load: function(event) {
            var total = 0; // get total of data
            for (var i = 0, len = this.series[0].yData.length; i < len; i++) {
                total += this.series[0].yData[i];
            }
            var text = this.renderer.text(
                'Total: ' + total,
                this.plotLeft,
                this.plotTop - 20
            ).attr({
                zIndex: 5
            }).add() // write it to the upper left hand corner
        }
    }
},

小提琴example

enter image description here

答案 1 :(得分:5)

除了Mark的答案,要计算总数,我们不需要for-loop语句。因此,代码可以减少。

chart: {
    events: {
        load: function(event) {
            var total = this.series[0].data[0].total;
            var text = this.renderer.text(
                'Total: ' + total,
                this.plotLeft,
                this.plotTop - 20
            ).attr({
                zIndex: 5
            }).add() // write it to the upper left hand corner
        }
    }
},