Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3 change the charge of a single node

When I click on a node, my node get bigger, and as it's now bigger, I would like his charge to repulse other node even more. How can I change the charge of a node ?

Code excerpt:

[...]

//draw new graph
d3.json(file, function(error, graph) {

force
.nodes(graph.nodes)
.links(graph.links)
.start();

var nodeCircle = node.append("circle")
.attr("id", function(d) { return "node"+d.id })
.attr("class", function(d) {return "node "+d.nodeclass; })
.attr("r", 8) // R = Radius of node
.style("fill", function(d) { return d.color; }) // Will overwrite CSS style
.on("click",function(d) {

    //When CTRL key is pressed ....
    if (d3.event.ctrlKey) {
        if(d3.select(this).attr('r')==8){
            d3.select(this).attr('r', 12);
            //ToDo: node Charge = -1000
        }else{
            d3.select(this).attr('r', 8);
            //ToDo: node Charge = -500
        }
    }

}).call(force.drag);
[...]
like image 285
FMaz008 Avatar asked May 17 '13 19:05

FMaz008


2 Answers

function click(d1,i){
    force.charge(
            function(d2,i){
                if(d2!=d1)
                    return ...;//calculate your charge for other nodes
                else
                    return ...;//calculate your charge for the clicked node
            });

        force.start();
 }

This works fine for me!! Correct me if Im wrong..!

like image 170
Boopathy Avatar answered Sep 18 '22 17:09

Boopathy


From the documentation:

force.charge([charge])

If charge is specified, sets the charge strength to the specified value. If charge is not specified, returns the current charge strength, which defaults to -30. If charge is a constant, then all nodes have the same charge. Otherwise, if charge is a function, then the function is evaluated for each node (in order), being passed the node and its index, with the this context as the force layout; the function's return value is then used to set each node's charge. The function is evaluated whenever the layout starts.

So what you need to do is specify a function for charge() that gives the different charge for the node in question and start the layout again.

like image 23
Lars Kotthoff Avatar answered Sep 18 '22 17:09

Lars Kotthoff