首页 > 解决方案 > 在饼图中显示百分比值

问题描述

console.log(group1.top(Infinity));

给我:

0:
key: "M"
value: {Recovered: 122, Hospitalized: 38922, Deceased: 641, Migrated_Other: 1}
__proto__: Object
1:
key: "F"
value: {Recovered: 82, Hospitalized: 19215, Deceased:.....

在这段代码中:

.label(function(d) {
                    return d.key+": " + (d.value[type]/<?> * 100).toFixed(2) + "%";
                })

如果type是,Recovered那么我想要恢复值的总和 (122+82) 代替<?>ied.value["Recovered"]/(122+82)

我只是停留在如何用匹配类型的值之和代替 <?> 的语法上。

我只能想到

group1.all()[0].value['Recovered']+group1.all()[1].value['Recovered']

有没有更好的办法?

工作代码: https ://blockbuilder.org/ninjakx/61d405cb0aaeda3be960e836f803cdd5

标签: dc.js

解决方案


有几种方法可以做到这一点。一种是手动计算总和,如上所示,或使用groupAll对象。

饼图示例使用的另一种方法是使用保存在饼图切片中的角度数据:

// workaround for #703: not enough data is accessible through .label() to display percentages
 .on('pretransition', function(chart) {
     chart.selectAll('text.pie-slice').text(function(d) {
         return d.data.key + ' ' + dc.utils.printSingleValue((d.endAngle - d.startAngle) / (2*Math.PI) * 100) + '%';
     })
 }); 

如前所述,没有提供足够的数据.label()来使用此方法,因此在绘制后使用完整的数据对象应用此方法。


推荐阅读