Accepted answer

Legends are just rectangle and text you append to svg. Check out population pie chart template on It has legend built into the chart:

To center the chart, change translate parameter in svg. You have it set to r right now. You can do something like, (width / 2 - r) and (height / 2 - r).

var svg ="#canvas").append("svg")
    .attr("width", width)
    .attr("height", height)
    .attr("transform", "translate(" + (width / 2 - r) + "," + (height / 2 - r) + ")");


Here is the example I ran off of But you will need d3.legend.js which you should be able to find off that link. Add that in and then do three things.

1st. Add a css class for legend

.legend rect {
 opacity:0.8; }

2nd. Add the attr: data-legend to g.append("path")

            .attr("d", arc)
            .attr("data-legend", function(d){return})
            .style("fill", function (d) { return color(; });

3rd. Some where after this go ahead and drop this guy in there

legend = svg.append("g")
            .attr("class", "legend")
            .attr("transform", "translate(50,30)")
            .style("font-size", "12px")

Then you should have a nice simple legend. If you want to center it, play with values in translate when creating legend (50, 30).

This is what you should end up with. enter image description here

Related Query

More Query from same tag