Make Nvd3 Pie Chart show percentages with decimal places

I am using Nvd3 in an Angular project to draw some diagrams. I am using the Angular directive from Krispo ( http://krispo.github.io/angular-nvd3/#/ ).

I am showing a pie chart whose labels show values โ€‹โ€‹as percentages, but the values โ€‹โ€‹shown are rounded and displayed without decimal places. See an example in the plunger below: http://plnkr.co/edit/jSf1TAkj5rO1S7p5PuJK?p=preview

In the example above, the percentages should be, for example, 21.9% and 78%.

I can only change the format of the slice value, not the label, which in this case is the percentage.

This is a big problem when I have a slice that is worth around 100% because it should show something like 99.99% instead of 100% giving the impression that there is only one slice.

Here is the diagram configuration:

chart: {
        type: 'pieChart',
        height: 500,
        x: function(d){return d.key;},
        y: function(d){return d.y;},
        showLabels: true,
        transitionDuration: 500,
        labelThreshold: 0.01,
        legend: {
              margin: {
                 top: 5,
                 right: 35,
                 bottom: 5,
                 left: 0
              }
        },
        labelType: 'percent',
        valueFormat: function(d) {
              return d3.format(',.5f')(d);
        }
 }

      

+3


source to share


3 answers


The nvd3 library seems to prevent you from changing this: https://github.com/novus/nvd3/blob/master/nv.d3.js#L10490

"percent": d3.format('%')(percent)

      



if you really need it, maybe add another labelType to the nvd3.js code with what you want

var labelTypes = {
     "key" : getX(d.data),
     "value": getY(d.data),
     "percent": d3.format('%')(percent),
     "percent2digits": d3.format('.2%')(percent)
 };

      

+3


source


I studied the same thing. Looking into the code of nv.d3.js, I found that labelType takes a function,

labelType: function(d){
      var percent = (d.endAngle - d.startAngle) / (2 * Math.PI);
      return d3.format('.2%')(percent);
    }

      



Passing this as part of the pie chart configuration gives labels with two decimal places.

+9


source


I suggest you a way to show the decimal part of the values โ€‹โ€‹using labelType('percent')

. The trick is to calculate percentage instead of nvd3, for example:

value = (value/tot)*100

      

This way you can calculate each percentage and show, for example, 3 digits after the decimal point like this:

value = (value/tot)*100).toFixed(3)

      

I am attaching a fiddle for clarity

I hope this is helpful

Hello

0


source







All Articles