首页 > 解决方案 > HighCharts:饼图中未显示总值

问题描述

我正在尝试在饼图上显示用户总数。但是我的“获取总代码”不起作用。它什么也不显示。

这是我正在使用的代码:

events: {
        load: function(event) {
          var total = 0;
            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()
        }
          }

如果我可以在这里向您展示我的完整代码:

var data = <?php echo $data ; ?>

data.forEach(function(el) {
el.name = el.label;
el.y = Number(el.value);
});

Highcharts.chart('pieDiv', {
chart: {

    plotBackgroundColor: null,
    plotBorderWidth: null,
    plotShadow: false,
    type: 'pie',
    events: {
        load: function(event) {
          var total = 0;
            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()
        }
          }
},
title: {
    text: undefined
},
credits: {
  enabled: false
},
exporting: { enabled: false } ,
tooltip: {
    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b> ({point.y} 
Users)'
},
plotOptions: {
    pie: {
colors: 
Highcharts.map(["#59deed","#e86e65","#de8f14","#589bcf","#a05195","#35cc95", 
"#72a7b3"], function (color) {
    return {
        radialGradient: {
            cx: 0.5,
            cy: 0.3,
            r: 0.7
        },
        stops: [
            [0, color],
            [1, Highcharts.Color(color).brighten(-0.3).get('rgb')] // darken
        ]
    };
 }),
         states: {
        inactive: {
            opacity: 1
        }
    },
        allowPointSelect: true,
        cursor: 'pointer',
        fillOpacity: 1,
         showInLegend: true,
        dataLabels: {
            enabled: true,
            format: '<b>{point.name}</b>: {point.percentage:.1f} % <br/> 
({point.y} Users)',
             style: {
                color: (Highcharts.theme && 
Highcharts.theme.contrastTextColor) || 'black'
            }
        }

    }
},
series: [{
    name: 'Users',
    colorByPoint: true,
    data: data
}]
});

我能够获取饼图上的数据。但未显示总计。它应该出现在盒子的左上角

标签: javascriptphphighcharts

解决方案


您在 js 中使用,而不是.for 循环代码犯了一个简单的错误;。检查代码和工作演示以及正确呈现的总数据。

代码:

  chart: {
    events: {
      load: function() {
        var total = 0,
          len = this.series[0].yData.length,
          text;

        for (var i = 0; i < len; i++) {
          total += this.series[0].yData[i];
        }

        text = this.renderer.text(
          'Total: ' + total,
          this.plotLeft,
          this.plotTop - 20
        ).attr({
          zIndex: 5
        }).add();
      }
    }
  }

演示:


推荐阅读