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

8

我有一个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>

数据

Data1=[{ key: "Ongoing", y: 20 },       { key: "completed", y: 0 }];

这是一个用于显示关键信息的工具提示功能。
$scope.toolTipContentFunction = function(){
    return function(key, x, y, e, graph) {
       return '<h1>' + key + '</h1>'
    }
}
3个回答

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>';
};

此外,当您创建NVD3图表时,如您所知,您需要添加此行:
.tooltipContent(tp);

最终结果是:

在此输入图片描述


3

稍作修改的 @VividD 回答。

(nvd3 版本 1.8.1)可以仅修改工具提示中的值(而不是所有文本):

var total = 0;
data.forEach(function (d) {
    total = total + d.value;
});

chart.tooltip.valueFormatter(function(d){
    return (d * 100/total).toFixed() + ' %';
});

Example: http://jsfiddle.net/mq56p4zk/4/


您能否详细阐述一下您的答案,并对您提供的解决方案进行更多描述? - abarisone

-1

类似于workgena,这个对我很有用。

chart.tooltip.valueFormatter(function(d){
    return (d +' %');
});

这只是在值后面添加了一个百分号,看起来不像操作者想要的。 - Martin Schilliger

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接