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

user659025 picture user659025 · Jul 6, 2015 · Viewed 36.2k times · Source

I'm currently working on a small genealogy experiment and would like to implement a simple family tree like in the picture below.

The best search results so far for this only yielded examples where a child can only have a parent node. But what I need is the ability to create links between entities (from father to mother) and links between nodes and other links (from child to the father-mother link). Currently I don't have a fixed data schema for this.

I've chosen d3.js for this because it looks like would be capable of doing the job. I just don't know how or even where to start. Tutorials about d3.js only cover standard charts like bar charts.

I hope someone can help me with this.

This is how the result should look like

Answer

Cyril Cherian picture Cyril Cherian · Jul 12, 2015

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.