Appending different element types on enter

1,281 views
Skip to first unread message

Jamie Popkin

unread,
Aug 2, 2011, 3:09:49 PM8/2/11
to d3...@googlegroups.com
I'm having loads of fun playing with the force layouts. I've got a quick question.

On entering an array and appending elements I was wondering if there is some way to add different types of elements depending on the output of a function... Or some other means.

For example... I've got this little mock-up and would like to make the blue circles be text instead.

It would be super handy to have something like this work:

node = vis.selectAll("circle.node")
      .data(json.nodes)
      .enter().append(function (e) {
                if (e.blah === "text") {
                    return ("svg:text");
                } else {
                    return ("svg:circle");
                }
        });

But I don't think that's possible.

Any ideas would be much appreciated. :)
Thanks

Jamie

--
Jamie Popkin
Little Earth

Mike Bostock

unread,
Aug 2, 2011, 3:35:10 PM8/2/11
to d3...@googlegroups.com
Yeah, you can, using the `filter` operator. I'd probably start by
defining the nodes using a generic svg:g element:

node = vis.selectAll("g.node")
.data(json.nodes)
.enter().append("svg:g");

The nice thing about svg:g is that you can position all nodes
(regardless of how they are displayed) using the "transform"
attribute, translate(x,y). Then, use the filter operator to add
different contents:

node.filter(function(d) { return d.blah == "text"; }).append("svg:text")…
node.filter(function(d) { return d.blah != "text"; }).append("svg:circle")…

Mike

Jamie Popkin

unread,
Aug 2, 2011, 3:40:13 PM8/2/11
to d3...@googlegroups.com
Fantastic! Thanks Mike. :)


--
Jamie Popkin
Little Earth



Jamie Popkin

unread,
Aug 2, 2011, 6:38:15 PM8/2/11
to d3...@googlegroups.com
Thanks Again Mike. That worked like a charm.

Here is the result displaying text nodes linked to circle nodes.
     http://littleearth.ca/d3/labels.html

Now I'm planning to tinker with how the links attach. I'm hoping to have the link target float to the best locating on the text <g>.

This has been a fun project :)

Jamie

Oyindamola Oluwatimi

unread,
Mar 24, 2015, 11:15:24 AM3/24/15
to d3...@googlegroups.com, mbos...@cs.stanford.edu
This filtering function allows different rending options (i.e., text or circle). 

I am using d3.layout.tree() (collapsible tree) and I want to perform a binary conditional rendering of a parent node. That is, either render this node or not. Of course, if the parent node is not rendered and it also has children, then the children will not be rendered as well. 

Can I accomplish this with this filtering method?

Link to collapsible tree: http://bl.ocks.org/mbostock/4339083
Reply all
Reply to author
Forward
0 new messages