如何在nvd3饼图的工具提示中获得百分比?

vip*_*pin 8 javascript svg d3.js pie-chart nvd3.js

我有一个nvd3饼图.我获取百分比值作为标签,但我想在工具提示中.这是HTML:

<nvd3-pie-chart data="Data1"id="labelTypePercentExample"
      width="550"
      height="350"
      x="xFunction()"
      y="yFunction()"
      showLabels="true"
      pieLabelsOutside="false"
      tooltips="true"
      tooltipcontent="toolTipContentFunction()"
      labelType="percent"
      showLegend="true">
  </nvd3-pie-chart>
Run Code Online (Sandbox Code Playgroud)

数据

Data1=[{ key: "Ongoing", y: 20 },
       { key: "completed", y: 0 }];
Run Code Online (Sandbox Code Playgroud)

这是用于将键显示为工具提示数据的工具提示功能.

$scope.toolTipContentFunction = function(){
    return function(key, x, y, e, graph) {
       return '<h1>' + key + '</h1>'
    }
}
Run Code Online (Sandbox Code Playgroud)

Viv*_*idD 7

这是一个jsfiddle,用于显示工具提示中的百分比.

关键代码是:(您必须计算包含饼图的所有值的总和)

var data = [
    {"label": "Water",        "value": 63}, 
    {"label": "Milk",         "value": 17}, 
    {"label": "Lemonade",     "value": 27},
    {"label": "Orange Juice", "value": 32}
];

var total = 0;
data.forEach(function (d) {
    total = total + d.value;
});
var tp = function(key, y, e, graph) {
    return '<p>' +  (y * 100/total).toFixed(3) + '%</p>';
};
Run Code Online (Sandbox Code Playgroud)

此外,您在创建NVD3图表时添加此行,如您所知:

.tooltipContent(tp);
Run Code Online (Sandbox Code Playgroud)

最终结果:

在此输入图像描述