How to obtain percentage in tooltips of an nvd3 pie chart?
Asked Answered
T

3

8

I have an nvd3 pie chart. I am obtaining the percentage value as labels but I want it in the tooltip. Here is the 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>

DATA

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

Here is the tooltip function for showing key as tooltip-data.

$scope.toolTipContentFunction = function(){
    return function(key, x, y, e, graph) {
       return '<h1>' + key + '</h1>'
    }
}
Terza answered 8/7, 2014 at 4:38 Comment(0)
Z
7

Here is a jsfiddle that demonstrates percentage in tooltips.

The key code is this: (you have to calculate total of all values that comprise pie chart)

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

Also, you add this line when you create NVD3 chart, as you already know:

.tooltipContent(tp);

The end result:

enter image description here

Zephyrus answered 14/2, 2015 at 17:6 Comment(0)
S
3

Slightly modified @VividD answer.

It is possible(nvd3 v 1.8.1) to modify only the value in tooltip (not all the text):

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/

Sacerdotal answered 22/9, 2015 at 12:47 Comment(1)
Could you please elaborate more your answer adding a little more description about the solution you provide?Seeress
K
-1

Similar to workgena, this did it for me.

chart.tooltip.valueFormatter(function(d){
    return (d +' %');
});
Kauppi answered 5/3, 2016 at 20:55 Comment(1)
This only adds a Percent-Sign behind the value, doesn't look like tha OP wanted.Perloff

© 2022 - 2024 — McMap. All rights reserved.