@addison
To add a legend to a pie chart in d3.js, you can follow these steps:
1
|
var legendData = ["Category 1", "Category 2", "Category 3"]; |
1 2 3 4 5 6 |
var svg = d3.select("body") .append("svg") .attr("width", 100) .attr("height", 100) .append("g") .attr("transform", "translate(0, 20)"); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
var legend = svg.selectAll(".legend") .data(legendData) .enter() .append("g") .attr("class", "legend") .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; }); legend.append("rect") .attr("width", 18) .attr("height", 18) .style("fill", function(d, i) { return color(i); }); legend.append("text") .attr("x", 24) .attr("y", 9) .attr("dy", ".35em") .text(function(d) { return d; }); |
By following these steps, you can add a custom legend to your pie chart in d3.js.