首页 > 解决方案 > 饼图中心的所需标签未呈现 DC/D3.js

问题描述

使用下面的示例图表/代码,一切都很好,除了我的饼图中心标签指示总数。如何让这个文本出现在我的饼图中间?

在此处输入图像描述

$scope.openRiskCharts = function(){

     $scope.riskChart = new dc.pieChart('#risk-chart', 'risk');
      $scope.riskChart.ordinalColors(["#00b050", "#eeee00", "#ee0000"]);
     var levelCounts = [
                {Level: 'High', Count: 13},
                {Level: 'Med', Count: 43},
                {Level: 'Low', Count: 60}
     ];

     // set crossfilter
     var ndx = crossfilter(levelCounts),
        levelDim  = ndx.dimension(function(d) {return d.Level;}),
        countPerLevel = levelDim.group().reduceSum(function(d) {return +d.Count});

     var riskchart = document.getElementById('risk-chart'); 


     height = Math.floor(riskchart.offsetHeight) 
      - 2*parseInt(window.getComputedStyle(riskchart, null).getPropertyValue('padding-top'));
     width =  55
        + Math.floor(parseFloat(window.getComputedStyle(riskchart, null).width))
      - 2*parseInt(window.getComputedStyle(riskchart, null).getPropertyValue('padding-top'));    

     $scope.riskChart
        .dimension(levelDim)
        .group(countPerLevel)
        .width(width)
        .height(height)
        .radius(Math.round(height/2.0))
        .innerRadius(Math.round(height/5.0))
        .controlsUseVisibility(true)
        .transitionDuration(250);

    //HERE NOTHING APPEARS IN MY CHART CENTER, HOW DO I FIX?    

    var svg = d3.select("svg g:first-of-type"); // select the svg element where you are putting your pie chart.
    svg.enter().append("text") // appent the "text" element
      .attr("text-anchor", "middle")
      .text("142 Open Risks");

   $scope.riskChart.render();


    $scope.openChart = new dc.starChart('#risk-chart', 'blue', 55, 55);
    $scope.openChart.redraw('blue');                            
}

标签: javascriptd3.js

解决方案


修改我的渲染方法(标签生成代码)以发生在包装的预转换块中以考虑图形的渲染时间产生了正确的结果。

 $scope.riskChart.on('pretransition', function(chart) {             
     d3.select("g.pie-slice-group")
       .append("text") // appent the "text" element
       .attr("text-anchor", "middle")
       .attr('font-size', "15pt")
       .attr('font-weight', "bold")
       .text("142 Risks");     
 }); 

推荐阅读