roberto tomás
roberto tomás

Reputation: 4687

Fixed nodes not being fixed (d3 Force Directed Graph)

I am setting the nodes to be fixed with

let link = svg.append("g")
  .attr("class", "links")
  .selectAll("line")
  .data(graph.links)
  .enter().append("line")
  .attr("stroke-width",  () => 4)

let node = svg.append('g')
  .attr("class", "nodes")
  .selectAll(".node")
  .data(graph.nodes)
  .enter().append("g")
  .attr("class", "node")
  .call(
    d3.drag()
    .on("start", Node.dragstarted)
    .on("drag", Node.dragged)
    .on("end", Node.dragended))

node.append("title")
  .text(d => d.country)

node.append('image')
    .attr('xlink:href', d => 'https://rawgit.com/hjnilsson/country-flags/master/svg/' + d.code + '.svg')
    .attr('height', d => 2.5 * (area[d.code]||5))
    .attr('width', d => 4 * (area[d.code])||5)
simulation
  .nodes(graph.nodes.map(c => {
    if(latlong[c.code] === undefined) {
      console.log(c,'missing lat/long data')
      return c
    }
    c.x = (+latlong[c.code][0])
    c.y = (+latlong[c.code][1])
    c.fixed = true
    return c
  }))
  .on("tick", ticked)

This does correctly display images in apparently different locations than without the x and y values, but .. the fixed property isn't working.

Here's my code: codepen

If anyone also knows how I can set the canvas up so that nothing escapes out the top or bottom I'd appreciate that as well.

Upvotes: 1

Views: 1060

Answers (1)

Andrew
Andrew

Reputation: 13853

d3.js v4 does not have a fixed property. Instead, you need to set the nodes fx and fy attributes. Note, your drag functions are already doing this.

.nodes(graph.nodes.map(c => {
if(latlong[c.code] === undefined) {
  console.log(c,'missing lat/long data')
  return c
}
c.fx = c.x = (+latlong[c.code][0])
c.fy = c.y = (+latlong[c.code][1])
return c
}))

https://codepen.io/anon/pen/ZKXmVe

Upvotes: 3

Related Questions