d3 rect没有出现



我想显示一些数据的图例(标题?)。对于图例的每一部分,我都会在父除法后附加一个rect和一个p。问题是rect没有出现。

这是我的代码:

var groups = {{ groups|safe }};
groups.forEach(function(group, i) {
    var div = d3.select("#collapse-legend");
    div.append("rect")
        .attr("width", 17)
        .attr("height", 17)
        .style("fill-opacity", 1)
        .style("fill", function (d) { return c(i); });
    div.append("p").text(group)
});

现在,当我检查网页的内容时,我得到了rect和p,但rect:

  1. 没有出现
  2. 宽度似乎为0(用firefox显示其区域)

我的代码有错误吗?有更好的方法来实现这一点吗?我是javascript和d3.js的新手,所以请宽容^^

更新

这就是我的结局
HTML:

<div ...>
    <svg id="legend-svg"></svg>
</div>

JavaScript:

// set height of svg
d3.select("#legend-svg").attr("height", 18*(groups.length+1));
// for each group, append rect then text
groups.forEach(function(group, i) {
    d3.select("#legend-svg").append("rect")
        .attr("y", i*20)
        .attr("width", 18)
        .attr("height", 18)
        .style("fill-opacity", 1)
        .style("fill", function (d) { return c(i); });
    d3.select("#legend-svg").append("text")
        .attr("x", 25)
        .attr("y", i*20+15)
        .text(group);
});

类似<rect>的SVG元素不能是html <div>元素的直接子元素。您必须将它们放在<svg>容器元素中。

设置rect:的X+Y值

.attr("x", 50)
.attr("y", 50)

最新更新