redixhumayun
redixhumayun

Reputation: 1844

Links not showing up in D3 v4 Force layout

I am developing a D3 Force layout that displays different countries as circles and shows the countries that share borders as links between their respective nodes.

Here is the dataset https://raw.githubusercontent.com/DealPete/forceDirected/master/countries.json

Here is the codepen http://codepen.io/redixhumayun/pen/ZLELvG?editors=0010

For some reason, the nodes show up, but my links don't. When I use DevTools to inspect them, they have a position of 0x0. I have no idea why this is.

Here is the relevant code.

//Creating force layout simulation object
  var simulation = d3.forceSimulation(data_nodes)
                .force('link', d3.forceLink().id(function(d){ return d.id }))
                .force('charge', d3.forceManyBody())
                .force('center', d3.forceCenter(width / 2, height / 2));

//creating a variable for the links where the data will be stored
  var link = svg.selectAll('.link')
                .append('g')
                .data(data_links)
                .enter().append('line')
                .attr('class', 'link')
                .attr('stroke-width', function(d){ return 8 })

simulation
      .nodes(data_nodes)
      .on('tick', ticked);

simulation.force('link')
            .links(link);

  function ticked(){
    link.attr('x1', function(d){ return d.source.x; })
        .attr('y1', function(d){ return d.source.y; })
        .attr('x2', function(d){ return d.target.x; })
        .attr('y2', function(d){ return d.target.y; });

    node.attr('cx', function(d) { return d.x; })
        .attr('cy', function(d) { return d.y; })
        .on('mouseover', function(d){
           console.log(d.country);
        })
  }

Upvotes: 1

Views: 2928

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

Just set the color of the lines:

.attr("stroke", "black")

Besides that, since your links array uses the numeric indices of the nodes, you don't need to set the id in the force:

.id(function(d){ return d.id })

Here is your updated CodePen: http://codepen.io/anon/pen/qRExJe?editors=0010

Upvotes: 3

Related Questions