How can I draw links between nodes with D3.js?

Viewed 120

I am drawing a force directed graph with D3.js

I have my nodes working correctly but the lines are missing:

nodes without lines.

How can I show the lines?

    var width = 300, height = 300
    var nodes = [{}, {}, {}, {}, {}]
    var links = [
        {source: 0, target: 1},
        {source: 0, target: 2},
        {source: 0, target: 3},
        {source: 3, target: 4},]

    var simulation = d3.forceSimulation(nodes)
        .force('charge', d3.forceManyBody())
        .force('center', d3.forceCenter(width / 2, height / 2))
        .force('link', d3.forceLink().links(links))
        .on('tick', ticked); 

    function ticked() {
        var u = d3.select('svg')
        .selectAll('circle')
        .data(nodes)
        .join('circle')
        .attr('r', 5)
        .attr('cx', function(d) {
  return d.x
        })
        .attr('cy', function(d) {
        return d.y
        });}
1 Answers

Draw links with a <line> element:

const width = 100;
const height = 100
const nodes = [{}, {}, {}, {}, {}]
const links = [
  {source: 0, target: 1},
  {source: 0, target: 2},
  {source: 0, target: 3},
  {source: 3, target: 4}
];

const simulation = d3.forceSimulation(nodes)
  .force('charge', d3.forceManyBody())
  .force('center', d3.forceCenter(width / 2, height / 2))
  .force('link', d3.forceLink().links(links))
  .on('tick', ticked); 

 function ticked() {
  const svg = d3.select('svg');
  svg.selectAll('circle')
    .data(nodes)
    .join('circle')
    .attr('r', 5)
    .attr('cx', d => d.x)
    .attr('cy', d => d.y);
    
  svg.selectAll('line')
    .data(links)
    .join('line')
    .attr('x1', d => d.source.x)
    .attr('x2', d => d.target.x)
    .attr('y1', d => d.source.y)
    .attr('y2', d => d.target.y)
    .style('stroke', 'black')
    
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.0.0/d3.min.js"></script>

<svg width="200" heihgt="250" />

Related