Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to update specific node in D3

Tags:

d3.js

I'm living updating nodes and links. I also want to change the radius of existing nodes(circles). how can i update eg a specific circle?

  • When i do this below it updates all circles.

    node.select("circle").attr("r", circleradius); 
    
  • when i update the node array nothing changes in the viz.

    nodes[index].size = 2000;
    

this is how the outputted html looks like

this is the function update code:

    function update() {


        // Restart the force layout.
        force
            .nodes(nodes)
            .links(links)
            .start();


        // Update links.
        link = link.data(links, function(d) { return d.target.id; });

        link.exit().remove();

        link.enter().insert("line", ".node")
            .attr("class", "link");

        // Update nodes.
        node = node.data(nodes, function(d) { return d.id; });

        node.exit().remove();

        var nodeEnter = node.enter().append("g")
            .attr("class", "node")
            .on("click", click)
            .call(force.drag); 

        nodeEnter.append("circle")
                .attr("r", function(d) {   return Math.sqrt(d.size) / 2 || 24.5; });

        nodeEnter.append("text")
                      .attr("dy", ".35em")
                      .text(function(d) { return d.name; });

        node.select("circle")
            .style("fill", color);

    }
like image 969
Dave Driesmans Avatar asked Mar 24 '26 18:03

Dave Driesmans


1 Answers

Child elements are not automatically updated until you use d3.select. It's a bit of a hard thing to wrap your head around which I won't get into here.

But for practical purposes, what you need to do is, after you've created your force-directed layout and elements and such, if you want to change a data value used for size element 0 and see it update, the code needs to read like this:

 nodes[0].size = 2000;
 d3.selectAll("g").select("circle")
  .attr("r", function(d) {   return Math.sqrt(d.size) / 2 || 24.5; });
like image 94
Elijah Avatar answered Mar 26 '26 09:03

Elijah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!