73

I am working on a force directed graph in D3. I want to highlight the mouseover'd node, its links, and its child nodes by setting all of the other nodes and links to a lower opacity.

In this example, http://jsfiddle.net/xReHA/, I am able to fade out all of the links and nodes then fade in the connected links, but, so far, I haven't been able to elegantly fade in the connected nodes that are children of the currently mouseover'd node.

This is the key function from the code:

function fade(opacity) {
    return function(d, i) {
        //fade all elements
        svg.selectAll("circle, line").style("opacity", opacity);

        var associated_links = svg.selectAll("line").filter(function(d) {
            return d.source.index == i || d.target.index == i;
        }).each(function(dLink, iLink) {
            //unfade links and nodes connected to the current node
            d3.select(this).style("opacity", 1);
            //THE FOLLOWING CAUSES: Uncaught TypeError: Cannot call method 'setProperty' of undefined
            d3.select(dLink.source).style("opacity", 1);
            d3.select(dLink.target).style("opacity", 1);
        });
    };
}

I am getting a Uncaught TypeError: Cannot call method 'setProperty' of undefined error when I try to set the opacity on an element I loaded from the source.target. I suspect this is not the right way to load that node as a d3 object, but I can't find another way to load it without iterating over all of the nodes again to find the ones that match the link's target or source. To keep the performance reasonable, I don't want to iterate over all the nodes more than necessary.

I took the example of fading the links from https://bl.ocks.org/mbostock/4062006:

enter image description here

However, that doesn't show how to alter the connected child nodes.

Any good suggestions on how to solve or improve this will be furiously upvoted :)

xxx
  • 1,153
  • 1
  • 11
  • 23
Christopher Manning
  • 4,527
  • 2
  • 27
  • 36

1 Answers1

97

The error is because you are selecting the data objects (d.source and d.target) rather than the DOM elements associated with those data objects.

You've got the line highlighting working, but I would probably combine your code into a single iteration, like this:

 link.style("opacity", function(o) {
   return o.source === d || o.target === d ? 1 : opacity;
 });

Highlighting the neighboring nodes is harder because what you need to know the neighbors for each node. This information isn't that easy to determine with your current data structures, since all you have as an array of nodes and an array of links. Forget the DOM for a second, and ask yourself how you would determine whether two nodes a and b are neighbors?

function neighboring(a, b) {
  // ???
}

An expensive way to do that is to iterate over all of the links and see if there is a link that connects a and b:

function neighboring(a, b) {
  return links.some(function(d) {
    return (d.source === a && d.target === b)
        || (d.source === b && d.target === a);
  });
}

(This assumes that links are undirected. If you only want to highlight forward-connected neighbors, then eliminate the second half of the OR.)

A more efficient way of computing this, if you have to do it frequently, is to have a map or a matrix which allows constant-time lookup to test whether a and b are neighbors. For example:

var linkedByIndex = {};
links.forEach(function(d) {
  linkedByIndex[d.source.index + "," + d.target.index] = 1;
});

Now you can say:

function neighboring(a, b) {
  return linkedByIndex[a.index + "," + b.index];
}

And thus, you can now iterate over the nodes and update their opacity correctly:

node.style("opacity", function(o) {
  return neighboring(d, o) ? 1 : opacity;
});

(You may also want to special-case the mouseovered link itself, either by setting a self-link for every node in linkedByIndex, or by testing for d directly when computing the style, or by using a !important css :hover style.)

The last thing I would change in your code is to use fill-opacity and stroke-opacity rather than opacity, because these offer much better performance.

mbostock
  • 51,423
  • 13
  • 175
  • 129
  • 1
    That works great @mbostock, thank you so much :D I've updated [the jsfiddle](http://jsfiddle.net/xReHA/1/) with your solution. – Christopher Manning Jan 09 '12 at 07:46
  • Mike, that solution was simply beautiful. Just sayin'. – Vivek Jul 11 '12 at 20:04
  • Mike, is there a way to get from the data object to the DOM element? I have written a method to get me all neighboring data nodes to a 'mouseovered' node. How can I change CSS/Style/Class/... on the DOM elements that belong to these data nodes? – fgysin Oct 16 '12 at 12:26
  • 1
    @fgysin Here are some possible methods: http://stackoverflow.com/questions/11206015/clicking-a-node-in-d3-from-a-button-outside-the-svg/11211391#11211391 – mbostock Oct 16 '12 at 14:56
  • Mike, could you update this solution for d3 v3? It would be nice to see a working example, but the new file locations are confusing jsfiddle no end. – ftrotter Feb 19 '13 at 07:44
  • @ftrotter Nothing in my answer changes from V2 to V3. And that's not my jsfiddle, so I can't change it. – mbostock Feb 23 '13 at 04:49
  • is there any reason why neither of the jsfiddles (question nor answer) are working now? – Nick Ginanto Mar 21 '13 at 11:51
  • @NickGinanto there is a 404 on the json data – kdazzle May 27 '13 at 17:16
  • @mbostock, how can one use this for force directed graph in 3d using three.js. I.e lines and mesh. I need to update the connected nodes on click? – looneytunes Jun 05 '15 at 01:51
  • 8
    As kdazzle said above, that fiddle tries to dynamically load json data, and both the data is no longer there and also jsfiddle doesn't want to load X-domain. Here's an updated fiddle that inlines the data: http://jsfiddle.net/tristanreid/xReHA/636/ – Tristan Reid Aug 03 '15 at 23:24
  • @mbostock : Can you please help me with issue in below post. My d3 tree is behaving weird. After 2 clicks on "More..." node , the tree does not behave as expected https://stackoverflow.com/a/72076145/1344006 – Carpe Diem May 02 '22 at 17:33
  • @TristanReid: Maybe you can update the jsfiddle to the new GitHub URLs (ending in `.io` instead of `.com`) because without that change the fiddle doesn't correctly load D3 and throws **Uncaught ReferenceError: d3 is not defined** - perfect otherwise! Thank you – Marcus Mangelsdorf Feb 06 '23 at 15:42