简体   繁体   中英

D3 JS creating a legend for a chart

I'm trying to make my own legend for a chart and at the moment the bars with the colours are appearing but not the text. Here is my code:

viz.selectAll("rect").data(data).enter().append("rect")
    .attr({
      x: margin,
      y: function (d, i) { return ((3*b)/data.length)*i; } ,
      width: 30,
      height: 15,
      fill: function(d, i) { return color(i); }
    })
.append("text").text(function (d) { return d.name; })
    .attr({
      "text-anchor" : "start",
      x: 2 * margin + parseFloat (d3.select(this).attr("width")), //doing 2* marging so I  can add some space between the text and the bar
      y: parseFloat(d3.select(this).attr("y"))
    });

I also tried changing both x and y to 0 in case I got the positioning wrong but that didn't work. When I tried to inspect the element using my browser, I noticed that it hasn't added the text at all. Am I doing this wrong?

You are adding the text to the rect which is not possible . You should add the text directly to the viz :

viz.selectAll("rect").data(data).enter().append("rect")
  .attr({
    x: margin,
    y: function (d, i) { return ((3*b)/data.length)*i; } ,
    width: 30,
    height: 15,
    fill: function(d, i) { return color(i); }
  });
viz.selectAll("text").data(data).enter().append("text")
  .text(function (d) { return d.name; }).attr({
    "text-anchor" : "start",
    x: 2*margin + 30,
    y: function (d, i) { return ((3*b)/data.length)*i; }
  });

Or, perhaps cleaner, create g elements and add the rect and text to that (used a slightly different example than yours because you didn't give your data):

  var vis = d3.select("#vis").append("svg")
    .attr("width", width).attr("height", height)

  var legend = ["red", "green", "blue"];
  var colors = ["#FF0000", "#00FF00", "#0000FF"];

  var margin = 10;

  vis.selectAll("g.legend").data(legend).enter().append("g")
    .attr("class", "legend").attr("transform", function(d,i) {
      return "translate(" + margin + "," + (margin + i*20) + ")";
    }).each(function(d, i) {
      d3.select(this).append("rect").attr("width", 30).attr("height", 15)
        .attr("fill", d);
      d3.select(this).append("text").attr("text-anchor", "start")
        .attr("x", 30+10).attr("y", 15/2).attr("dy", "0.35em")
        .text(d);
    });

Edit : The attr("dy", "0.35em") ensures that the centre of the line of text is horizontally aligned with the centre of the rect . See the d3 wiki for an overview .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM