Search code examples
d3.jsenter

How do I update multiple columns of data with D3?


I'm wanting to do something in D3 that's very similar to what this guy is trying to do:

Can enter() selection be reused after append/insert?

I have multiple (rows and) columns of data, and for every piece of data I need to bind it to several elements. The answer to the question I linked to above explains how this works with enter selections, but what about with update selections?

Basically, I need to know how that's supposed to work with setting the attributes in the update selection and knowing which piece of data is currently having its attributes set, etc. I can't find examples or documentation for this anywhere.



EDIT: Alright, I generally got it working. However, there's still one fundamental problem left: even though the data array that I'm passing in to the "data" function call is correct, the values passed to the "update" selection are incorrect.

I debugged it a little bit, and I think I know what's going on: the wrong data is getting removed in the exit selection. How do I fix this - in other words, how do I make sure that the old data is removed and the data that's repeated in my new "data" function call remains intact?

Just to clarify, let's say this is the data that I pass in (to the "data" function call):

1, 2, 3
4, 5, 6

then let's say I pass in this the next time around:

4, 5, 6

for some reason, this is the resulting data:

1, 2, 3

etc. How can I fix this, or is this not supposed to happen and is it only happening because I'm doing something wrong?

Also, in case it helps, if I select all "g" elements and remove them before I call the "data" function:

svg.selectAll("g").remove();

svg.selectAll("g").data(data);

then I don't experience this problem. Obviously, this is not an elegant solution though.


Solution

  • Continuing the example code from question you linked, you need to re-select the added lines:

    var g = svg.selectAll(".foo")
        .data([123, 456]);
    
    var gEnter = g.enter().append("g")
        .attr("class", "foo");
    
    gEnter.append("line"); // line1
    gEnter.append("line"); // line2
    
    var line = g.selectAll("line"); // line1 and line2
    

    (If you want to modify line1 or line2 separately, assign them separate classes or identifying attributes.)

    Conceptually, the parent G elements have an enter, update and exit selection as a result of the data-join. If you append child elements to the entering G's, you'll need to reselect them to create the merged enter+update selection of the children.