d3 rect 没有显示
d3 rect not showing up
我想显示一些数据的图例(标题?)。
对于图例的每个部分,我将一个 rect 和一个 p 附加到 parent 分区。
问题是 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:
- 没有出现
- 好像宽度为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);
});
设置矩形的 X + Y 值:
.attr("x", 50)
.attr("y", 50)
像 <rect>
这样的 SVG 元素不能是 html <div>
元素的直接子元素。您必须将它们放在 <svg>
容器元素中。
我想显示一些数据的图例(标题?)。 对于图例的每个部分,我将一个 rect 和一个 p 附加到 parent 分区。 问题是 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:
- 没有出现
- 好像宽度为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);
});
设置矩形的 X + Y 值:
.attr("x", 50)
.attr("y", 50)
像 <rect>
这样的 SVG 元素不能是 html <div>
元素的直接子元素。您必须将它们放在 <svg>
容器元素中。