乐闻世界logo
搜索文章和话题

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

1个答案

1

When creating a family tree with d3.js, you can follow these steps:

1. Collect Data

First, define the data structure for the family tree. This typically includes personal information such as names, birth dates, and family relationships. Data can be stored in JSON format, for example:

json
{ "name": "John Doe", "children": [ { "name": "Jane Doe", "children": [ {"name": "Jim Doe"}, {"name": "Jill Doe"} ] }, { "name": "Joe Doe" } ] }

2. Design the Layout

d3.js provides various layouts for rendering tree or hierarchical data. For a family tree, use d3.tree() or d3.cluster() layouts, both suitable for displaying hierarchical data.

3. Create an SVG Container

In your HTML file, create an SVG container to draw the family tree:

html
<svg width="960" height="600"></svg>

4. Draw the Family Tree

Use D3's data binding and rendering capabilities to bind each node to SVG elements and render it. You may need to add elements such as rectangles, text, and lines:

javascript
var tree = d3.tree() .size([height, width]); var nodes = d3.hierarchy(data); nodes = tree(nodes); var svg = d3.select("svg") .attr("width", width) .attr("height", height) .append("g") .attr("transform", "translate(40,0)"); var link = svg.selectAll(".link") .data(nodes.descendants().slice(1)) .enter().append("path") .attr("class", "link") .attr("d", function(d) { return "M" + d.y + "," + d.x + "C" + (d.y + d.parent.y) / 2 + "," + d.x + " " + (d.y + d.parent.y) / 2 + "," + d.parent.x + " " + d.parent.y + "," + d.parent.x; }); var node = svg.selectAll(".node") .data(nodes.descendants()) .enter().append("g") .attr("class", "node") .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; }); node.append("circle") .attr("r", 10); node.append("text") .attr("dy", ".35em") .attr("x", function(d) { return d.children ? -13 : 13; }) .style("text-anchor", function(d) { return d.children ? "end" : "start"; }) .text(function(d) { return d.data.name; });

5. Add Interactivity

Add interactive features such as clicking nodes to expand or collapse subtrees, or dragging to reorganize the family tree. This can be achieved by implementing event listeners and corresponding functions:

javascript
node.on("click", function(d) { if (d.children) { d._children = d.children; d.children = null; } else { d.children = d._children; d._children = null; } update(d); });

Example Project

In one project, I developed an interactive family tree display for a client. Using d3.js, we successfully implemented dynamic data loading and real-time updates of the family tree view, providing users with an intuitive and rich visual experience.

2024年7月25日 19:15 回复

你的答案