使用selectAll()创建新元素,同时保留现有元素

时间:2013-11-14 19:11:08

标签: svg d3.js

我正在努力学习一些d3教程,所以请忍受我的菜鸟问题。据我了解,为了创建某种类型的新元素,您必须对不存在的元素使用.selectAll(),然后使用.append()创建它们。当没有与指定选择器匹配的现有元素时,这很有效,但如果存在,它将选择那些/那些元素并在其中添加新元素。举个例子:

d3.json("virusOrigins.json", function(dataset) {
    var w = 200;
    var h = 300;
    var barPadding = 1;
    var xScale = d3.scale.linear()
                    .domain([0, d3.max(dataset, function(d) { return d.value; })])
                    .rangeRound([5, w])
                    .nice();

    var svg = d3.select("body")
        .append("svg")
        .attr("width", w)
        .attr("height", h)

        // append base rectangle
        .append("rect")
        .attr("width", w)
        .attr("height", h)
        .attr("fill", "#ccc");
    svg.selectAll("rect.bars")
        .data(dataset)
        .enter()
        .append("rect")
        .attr("y", function(d, i) {
            return i * (h / dataset.length);
        })
        .attr("x", 0)
        .attr("width", function (d) {
            return xScale(d.value);
        })
        .attr("height", function(d) {
            return (h / dataset.length) - barPadding;
        })
        .attr("fill", "#f33")
        .classed("bars", true);
});

这导致以下HTML:

<svg width="200" height="300">
    <rect width="200" height="300" fill="#ccc">
        <rect y="0" x="0" width="13" height="32.333333333333336" fill="#f33" class="bars"></rect>
        <rect y="33.333333333333336" x="0" width="5" height="32.333333333333336" fill="#f33" class="bars"></rect>
        <rect y="66.66666666666667" x="0" width="5" height="32.333333333333336" fill="#f33" class="bars"></rect>
        <rect y="100" x="0" width="5" height="32.333333333333336" fill="#f33" class="bars"></rect>
        <rect y="133.33333333333334" x="0" width="5" height="32.333333333333336" fill="#f33" class="bars"></rect>
        <rect y="166.66666666666669" x="0" width="200" height="32.333333333333336" fill="#f33" class="bars"></rect>
        <rect y="200" x="0" width="5" height="32.333333333333336" fill="#f33" class="bars"></rect>
        <rect y="233.33333333333334" x="0" width="5" height="32.333333333333336" fill="#f33" class="bars"></rect>
        <rect y="266.6666666666667" x="0" width="5" height="32.333333333333336" fill="#f33" class="bars"></rect>
    </rect>
</svg>

如何让动态创建的rect成为基本矩形的兄弟?

2 个答案:

答案 0 :(得分:1)

按如下方式更改数据插页:

svg.selectAll("rect.bars")
   .data(dataset, function(d){return d;}) <-- Here *
   .enter()
   .append("rect")
   ...
  • 添加函数以告知您要考虑不是现有元素的所有数据,而是真正生成新元素。

有关详细信息,请参阅本文的example 3,了解有关在D3.js中理解selectAll,data,enter,append sequence的内容。

答案 1 :(得分:1)

您将rect保存在svg中,然后附加到svg。只需保存var svg = d3.select("body") .append("svg") .attr("width", w) .attr("height", h); // append base rectangle svg.append("rect") .attr("width", w) .attr("height", h) .attr("fill", "#ccc"); svg.selectAll("rect.bars") .data(dataset) .enter() .append("rect") // etc 元素:

{{1}}