const data = { name: 'Root', children: [ { name: 'Child 1' }, { name: 'Child 2' }, { name: 'Child 3', children: [ { name: 'Grandchild 1' }, { name: 'Grandchild 2' }, ], }, ], }; const width = 600; const height = 400; const treeLayout = d3.tree().size([height, width - 100]); const rootNode = d3.hierarchy(data); const links = treeLayout(rootNode).links(); const nodes = rootNode.descendants(); const svg = d3.select('#tree').append('svg') .attr('width', width) .attr('height', height); svg.selectAll('line') .data(links) .enter().append('line') .attr('x1', d => d.source.y) .attr('y1', d => d.source.x) .attr('x2', d => d.target.y) .attr('y2', d => d.target.x) .attr('stroke', 'black'); const node = svg.selectAll('.node') .data(nodes) .enter().append('g') .attr('class', 'node') .attr('transform', d => `translate(${d.y},${d.x})`); node.append('circle') .attr('r', 4); node.append('text') .attr('dy', '.31em') .attr('x', d => d.children ? -8 : 8) .attr('text-anchor', d => d.children ? 'end' : 'start') .text(d => d.data.name);
const width = 600; const height = 400; const nodes = d3.range(20).map(() => ({ radius: Math.random() * 10 + 5 })); const links = d3.range(40).map(() => ({ source: Math.floor(Math.random() * nodes.length), target: Math.floor(Math.random() * nodes.length), })); const simulation = d3.forceSimulation(nodes) .force('charge', d3.forceManyBody()) .force('link', d3.forceLink(links)) .force('center', d3.forceCenter(width / 2, height / 2)); const svg = d3.select('#graph').append('svg') .attr('width', width) .attr('height', height); const link = svg.selectAll('.link') .data(links) .enter().append('line') .attr('class', 'link') .attr('stroke', '#ccc'); const node = svg.selectAll('.node') .data(nodes) .enter().append('g') .attr('class', 'node') .call(d3.drag() .on('start', dragStarted) .on('drag', dragged) .on('end', dragEnded)); node.append('circle') .attr('r', d => d.radius) .attr('fill', 'steelblue'); function ticked() { link .attr('x1', d => d.source.x) .attr('y1', d => d.source.y) .attr('x2', d => d.target.x) .attr('y2', d => d.target.y); node .attr('transform', d => `translate(${d.x},${d.y})`); } function dragStarted(d) { if (!d3.event.active) simulation.alphaTarget(0.3).restart(); d.fx = d.x; d.fy = d.y; } function dragged(d) { d.fx = d3.event.x; d.fy = d3.event.y; } function dragEnded(d) { if (!d3.event.active) simulation.alphaTarget(0); d.fx = null; d.fy = null; } simulation.on('tick', ticked);This code creates a force-directed graph based on randomly generated data, and uses the `d3.forceSimulation()` function to simulate the behavior of the nodes and links. The resulting visualization is rendered as an SVG element, with the nodes and links arranged in a visually pleasing manner. Overall, the D3 layout package is a powerful tool for creating complex visualizations in JavaScript, and it is commonly used in conjunction with other D3 packages to create dynamic, interactive data visualizations.