Sergei Basharov
Sergei Basharov

Reputation: 53850

Quickly represent numbers as percentages with D3

I seem to be facing a lot of tasks with D3 where I need to represent some value from an array as a percentage and it would be logic to have some nice D3 method to do it quickly and easily. For example, I have an array like [10, 20, 49, 75, 23, 102] and I want to put labels to a bar chart showing these numbers as percents of sum of all numbers in the array.

How would you recommend to handle these cases? One way is to run through this dataset before creating a chart and add a field to the object, like {value:10, asPercents:3} then put it in the respective action but I think it's used very often not only by me so that there must be a better builtin helper.

Upvotes: 0

Views: 531

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109232

Several of the D3 layouts do something like this (e.g. pie and stack), but there's no helper for this explicitly. It's reasonably easy to write a function to do that yourself though:

function percentize(data) {
  var sum = d3.sum(data);
  return data.map(function(d) {
    return { value: d, percent: d*100/sum };
  });
}

Upvotes: 1

Related Questions