简体   繁体   English

D3 JS为图表创建图例

[英]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. 我还尝试将x和y都更改为0,以防出现错误的定位,但是那没有用。 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 . 您正在将文本添加到rect ,这是不可能的 You should add the text directly to the viz : 您应该将文本直接添加到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): 或者,也许更干净一些,创建g元素并在其中添加recttext (使用了与您稍有不同的示例,因为您没有提供数据):

  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 . 编辑attr("dy", "0.35em")确保文本行的中心与rect的中心水平对齐。 See the d3 wiki for an overview . 有关概述,请参见d3 Wiki

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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