how do i update a d3.js force directed graph after i translated its nodes?

19 Views Asked by At

I am working with a directed graph via d3.js. In my code after i draw the graph on the svg, i can fix a vertical line, and by moving that line i can translate all nodes of the graph who have a higher x coordinate than the line. The issue i have is that after i translate successfully the nodes the links won't follow the nodes so i get a graph with disconnected links and nodes.

I tried restarting the simulation after the translation but it did not work, i know it should not be anything difficult but i'm a bit strict on time so i'd apppreciate if anyone could help me.

simulation = d3
  .forceSimulation(nodes)
  .on("tick", ticked);

  var link = svg
    .append("g")
    .attr("class", "links")
    .selectAll("line")
    .data(links)
    .enter()
    .append("line")

  var node = svg
    .append("g")
    .attr("class", "nodes")
    .selectAll("circle")
    .data(nodes)
    .enter()
    .append("circle")
    .call(
      d3
        .drag()
        .on("start", dragstarted)
        .on("drag", dragged)
        .on("end", dragended)
    );


  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;
      });
      transitiveLinks
      .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;
      });

  }
  function dragstarted(d) {
    if (!d3.event.active) simulation.alphaTarget(0.2).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;
  }

this is the d3 part of the code, and there instead is how i translate the nodes:


var filteredNodes = d3.selectAll(".nodes circle").filter(function(d) {
            return d.x > thresholdX;
          });
          filteredNodes.attr("transform", function(d) {
            return "translate ("+(mouseX-thresholdX)+",0)";
          });
          
          simulation.alphaTarget(0.2).restart();

this last code is part of the function that draws the line, but it has nothing to do with the nodes.

I added a pic of how i end up with nodes and links just to be clear, sorry again for the dumb question and thanks in advance.

0

There are 0 best solutions below