javascript-d3How can I create a collapsible tree with boxes using d3.js?
To create a collapsible tree with boxes using d3.js, we can use the following example code:
var root = {
"name": "root",
"children": [
{
"name": "level1",
"children": [
{ "name": "level2" }
]
}
]
};
var tree = d3.layout.tree()
.size([400, 200]);
var nodes = tree.nodes(root);
var svg = d3.select("body").append("svg")
.attr("width", 400)
.attr("height", 200);
var node = svg.selectAll(".node")
.data(nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
node.append("rect")
.attr("width", 10)
.attr("height", 10)
.attr("fill", "red");
node.append("text")
.attr("dx", 10)
.attr("dy", ".35em")
.text(function(d) { return d.name; });
This code will produce a collapsible tree with boxes as follows:
The code consists of the following parts:
- Create a JSON object representing the tree structure:
- The JSON object consists of a root node and its children nodes.
- Use the
d3.layout.tree()
function to create a tree layout:- This function takes the JSON object as an argument and returns a tree layout object.
- Create an SVG element to render the tree:
- Use the
d3.select()
function to select the body element and append an SVG element to it.
- Use the
- Create the nodes of the tree:
- Use the
node()
function of the tree layout object to create the nodes of the tree.
- Use the
- Create the boxes for each node:
- Use the
rect()
function to create a rectangle for each node.
- Use the
- Add text to each node:
- Use the
text()
function to add text to each node.
- Use the
Helpful links
More of Javascript D3
- How do I set up the x axis in d3.js?
- How can I use d3.js with W3Schools?
- How do I create a zoomable line chart using d3.js?
- How do I use D3.js to zoom on the x-axis?
- How do I implement zooming in a d3.js visualization?
- How do I use the viewbox feature in d3.js?
- How do I create a candlestick chart in d3.js?
- How do I use the z-index property with d3.js?
- How do I use d3.js to zoom to a selected area?
- How do I install and use D3.js with Yarn?
See more codes...