At the moment, the percentage displayed is hardcoded in the code. To replace this hardcoded percentage with the average of the data, you can substitute the 56%
with the actual average.
You can achieve this by leveraging the array of data used for calculating each donut chart, which is conveniently accessible as data
(initially named scope.data
). Here's how you can show the average:
svg.append("text")
.attr("dy", ".35em")
.style("text-anchor", "middle")
.attr("class", "inside")
.text(function(d) {
return data.reduce(function(a, b) { return a + b; }) / data.length;
});
Furthermore, as mentioned by Henry in the comments, a simpler approach would be to use d3.mean
instead of the reduce function. Thus, you can replace the previous block with:
return d3.mean(data);
You can view the outcome on this Plunker.
Most browsers that support d3 should also support the ECMA5 reduce method showcased here. Yet, if you intend to utilize this with a d3 shim like r2d3 for IE8 compatibility, consider incorporating an Array.prototype.reduce
polyfill, such as the one available from Mozilla.
Regarding the inquiry about labels, it's best to address it as a separate question. StackOverflow encourages one question per post. Once we conclude this discussion, feel free to post the label-related question, and I'll gladly assist.