score:3

Accepted answer

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

https://vida.io/documents/gSvr8dAH23eirKQDp

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 = d3.select("#canvas").append("svg")
    .attr("width", width)
    .attr("height", height)
  .append("g")
    .attr("transform", "translate(" + (width / 2 - r) + "," + (height / 2 - r) + ")");

score:11

Here is the example I ran off of http://bl.ocks.org/ZJONSSON/3918369 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 {
 fill:white;
 stroke:black;
 opacity:0.8; }

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

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

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")
            .call(d3.legend)

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