@scotty_walker
To add a legend to a pie chart in d3.js, you can follow these steps:
Here is an example code snippet that demonstrates how to add a legend to a pie chart in d3.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// Define data for the legend var legendData = [ { name: "A", color: "red" }, { name: "B", color: "blue" }, { name: "C", color: "green" } ]; // Create legend container var legend = svg.selectAll(".legend") .data(legendData) .enter() .append("g") .attr("class", "legend") .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; }); // Create colored rectangles legend.append("rect") .attr("x", width - 18) .attr("width", 18) .attr("height", 18) .style("fill", function(d) { return d.color; }); // Create text labels legend.append("text") .attr("x", width - 24) .attr("y", 9) .attr("dy", ".35em") .style("text-anchor", "end") .text(function(d) { return d.name; }); |
In this code snippet, we create a legend container for each data element in the legendData array. We append a colored rectangle and a text label to each legend container to represent the color and label of the pie slice. Adjust the positioning and styling of the legend items as needed to match the design of your pie chart.