How do you create a family tree in d3.js?

dTree is an open source library built on-top of D3 that creates family trees (or similar hierarchical graphs).

It handles the bothersome parts of generating the D3 graph manually and uses a simple json data format:

[{
  name: "Father",
  marriages: [{
    spouse: {
      name: "Mother",
    },
    children: [{
      name: "Child",
    }]
  }]
}]

If you are interested in modifying it supports callback for node rendering and event handler. Finally the library is as of 2016 under development and pull requests are welcomed.

DISCLAIMER: I'm the author of dTree. I created the library after searching the web just like you did and not finding anything to my liking.


My approach is as under:

Lets take the example you have illustrated in the attached figure:

Jenny Of Oldstones is also a the child of Aegon V but the difference between this child and other children of Aegon V is that in this case I am not drawing the link between it.

This is done by setting the node as no_parent: true in the node JSON example:

//Here Q will not have a parent
 {
            name: "Q",
            id: 16,
            no_parent: true
 }

In the code check the _elbow function_ this does the job of not drawing the line between it and its parent:

if (d.target.no_parent) {
    return "M0,0L0,0";
}

Next scenario is the link going between Node Aerys II and Rahella this node has its set of children.

  • I have created a node between them which is marked as hidden: true,
  • I make the display:none for such node. It appears that the children are coming from the line between node Aerys II and Rahella

JSON Example:

//this node will not be displayed
{ name: "",
    id: 2,
    no_parent: true,
    hidden: true,
    children: [....]

    }

In the code check the place where I make the rectangles, the code below hides the node:

    .attr("display", function (d) {
    if (d.hidden) {
        return "none"
    } else {
        return ""
    };
})

Full code is in here: http://jsfiddle.net/cyril123/0vbtvoon/22/

In the example above, I have made the use of node names A/B/C... but you can change it as per you requirements. You will need to center the text.

I have added comments to the code to help you understand the flow. Just in case you are not clear on any point please comment I ll be happy to clarify.