How to put a legend in a pie chart in d3.js?

Member

by addison , in category: Javascript , 4 months ago

How to put a legend in a pie chart in d3.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 4 months ago

@addison 

To add a legend to a pie chart in d3.js, you can follow these steps:

  1. Create a data array for the legend items, which should match the data used for the pie chart slices. For example:
1
var legendData = ["Category 1", "Category 2", "Category 3"];


  1. Create an SVG element to contain the legend items.
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. Add rectangles or circles to represent each legend item with corresponding colors.
 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; });


  1. Style the legend items as needed (e.g. font size, colors).
  2. Position the legend on the page as necessary by adjusting the attributes of the SVG element.


By following these steps, you can add a custom legend to your pie chart in d3.js.